Python Tricks

Checking a condition

condition = False

x = 1 if condition else 0

print (x)

Using spaces to easily read large numbers

num1 = 1_000_000_000
num2 = 1_000_000

total = num1 + num2

print(f'{total:,}')

# Output would be:
1,001,000,000

Using context managers

# This will automatically open and close the file
with open('file.txt, 'r') as f:
    for lines in f.readlines():
        print(lines)

Using enumerate

words = ['hello', 'world', 'hi', 'stuff']

for num, word in enumerate(words, start=1):
    print(f'{num} {word}')

Using zip to loop over multiple lists

name = ['mike', 'steve', 'james']
job = ['officer', 'teacher', 'hacker']

for name, job in zip(name, job):
    print(f'{name} {job}')

Unpacking

a, b, *c = (1, 2, 3, 4, 5)

print(a)
1
print(b)
2
print(c)
[3, 4, 5]



# If you want to ignore values 3, 4 and 5, you can use *_
a, b, *_ = (1, 2, 3, 4, 5)
print (a)
1
print (b)
2


# Another example
a, b, *c, d = (1, 2, 3, 4, 5)
print (a)
1
print (b)
2
print (c)
[3, 4]
print (d)
5

Last updated