List methods
dir(obj)
Print help
help(obj)
>>> [ord(x) for x in 'spaam'] # List of character ordinals
[115, 112, 97, 97, 109]
>>> {ord(x) for x in 'spaam'} # Sets remove duplicates
{112, 97, 115, 109}
>>> {x: ord(x) for x in 'spaam'} # Dictionary keys are unique
{'p': 112, 'a': 97, 's': 115, 'm': 109}
>>> (ord(x) for x in 'spaam') # Generator of values
<generator object <genexpr> at 0x000000000254DAB0>
open
function by uses os default encoding when tries to open a file (most of the time it’s utf-8), so if you want to read a binary file use:
with open('data.bin', 'rb') as f:
data = f.read()
for x in arr
instead of for i in range(arr)
if you need to get index and value at the same time use enumerate
flavor_list = ['vanilla', 'chocolate', 'pecan', 'strawberry']
for i, flavor in enumerate(flavor_list, 1):
print(f'{i}: {flavor}')
>>>
1: vanilla
2: chocolate
3: pecan
4: strawberry
names = ['Cecilia', 'Lise', 'Marie']
counts = [len(n) for n in names]
for name, count in zip(names, counts):
print(name, count)
if count := fresh_fruit.get('lemon', 0):
make_lemonade(count)
else:
out_of_stock()
# get the top from a list
car_ages = [0, 9, 4, 8, 7, 20, 19, 1, 6, 15]
car_ages_descending = sorted(car_ages, reverse=True)
oldest, second_oldest, *others = car_ages_descending
# header and body
it = generate_csv()
header, *rows = it