Python tips

Python assignment expression

This is one of the major changes in Python 3.8 is the introduction of Assignment expressions. It is written using := and is known as “the walrus operator”. The classic style:

key = ''
while(key != 'q'):
    key = input("Enter a number or q to exit ")
    if key != 'q':
        print(int(key)**2)

Using assignment operators:

while((key:= input("Enter a number or q to exit ")) != 'q'):
    print(int(key)**2)

Python program to generate a list of numbers up to x

limit = int(input("Enter the limit: "))
l = [x for x in range(limit+1)]
print(l)

This is known as list comprehension. Output:

Enter the limit: 5
[0, 1, 2, 3, 4, 5]

Reverse of a string

x = "Hello World"
print(x[::-1])

Output:

dlroW olleH

Create a dictionary from two lists

We can combine the elements of two lists as key-value pairs to form a dictionary. Here’s an example.

keys = ['Name', 'age']
values = ['John', '22']

d = {k:v for k, v in zip(keys, values)}
print(d)

Find Greatest Common Divisor(GCD)

import math

gcd1 = math.gcd(80, 160)
gcd2 = math.gcd(75, 125)

print(gcd1)
print(gcd2)

Output

80
25

Merge two dictionaries

dict1 = {"Ram": 100, "Shyam": 500 }
dict2 = { "Sita": 200, "Gita": 300}

dict3 = {**dict1, **dict2}

print(dict3)

Output

{'Ram': 100, 'Shyam': 500, 'Sita': 200, 'Gita': 300}

Arithmetic operators in strings and lists

str1 = "Welcome to"
str2 = "CodeFires!!!"

# concatenate strings
print(str1 +" "+ str2)

list1 = [4, 5, 6, 7]
list2 = [8, 9, 10, 11]

# concatenate lists
print(list1 + list2)

Output

Welcome to CodeFires!!!
[4, 5, 6, 7, 8, 9, 10, 11]

Extract numbers from string

# import python regex
import re

# initialise string
string = "Total 4 members climbed the height of 8848 meters in 2021"

# print original string
print("The original string : " + string)

# use re.findall()
temp = re.findall(r'\d+', string)

# as default type is string
# map string to int and make list
extracted_no = list(map(int, temp))

print(extracted_no)

Output

The original string : Total 4 members climbed the height of 8848 meters in 2021
[4, 8848, 2021]

Lambda

This lambda tip will help you to understand how lambda works. Lambda in Python is the user-defined one-line mini function.

num = lambda x: x**2print(num(5))

For loop with Else

You had usually use for loop alone but this tip will show you how you can use for loop with else statement.

for x in range(1, 4):    print(x)else:    print("Python")#output# 1# 2# 3# python