لَآ إِلَـٰهَ إِلَّا هُوَ
LA ILAHA ILLA HU
Allah, Your Lord There Is No Deity Except Him.

Lesson 9: Shortcuts In Python Coding

Python Shorcut Example Code1: How to Loop Over Multiple Lists at the Same Time.

Code

colors = ["red", "white", "black", "blue", "green", "yellow", "purple"]

codes = [1, 2, 3, 4, 5, 6, 7]

for color, code in zip(colors, codes):

print(f"{code}, {color}")


Output will be

1, red
2, white
3, black
4, blue
5, green
6, yellow
7, purple

Python Shorcut Example Code2: Important to remember that zip with different size lists will stop after the shortest list runs out of items.

Code

colors = ["red", "white", "black", "blue", "green"]

codes = [1, 2, 3, 4, 5, 6, 7]

for color, code in zip(colors, codes):

print(f"{code}, {color}")

Output will be

1, red
2, white
3, black
4, blue
5, green

Python Shorcut Example Code3: You may want to look into itertools.zip_longest if you need a different behavior.

Code

from itertools import zip_longest

colors = ["red", "white", "black", "blue", "green"]

codes = [1, 2, 3, 4, 5, 6, 7]

for color, code in zip_longest(colors, codes, fillvalue='Nothing'):

print(f"{code}, {color}")

output will be

1, red
2, white
3, black
4, blue
5, green
6, Nothing
7, Nothing

Python Shorcut Example Code4: for and if in One Line

Code

d = [1, 2, 1, 3, 1, 4]

a = [each for each in d if each == 1]

print(a)

output will be

[1, 1, 1]

Python Shorcut Example Code5: How to Loop With Index?

Code

list = ['a', 'b', 'c', 'd', 'e','f']

for index, value in enumerate(list):

print(f"{index}, {value}")

for index, value in enumerate(list, start=15):

print(f"{index}, {value}")

output will be

0, a
1, b
2, c
3, d
4, e
5, f
15, a
16, b
17, c
18, d
19, e
20, f

Python Shorcut Example Code6: How to Transpose 2D Array?

Code

chars = [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']]

transposed = zip(*chars)

print(list(transposed))

output will be

[('a', 'c', 'e'), ('b', 'd', 'f')]

Python Shorcut Example Code7: How to Transpose 2D Array if List Are Different In Length?

Code

from itertools import zip_longest

chars = [['a', 'b'], ['c', 'd'], ['g', 'h', 'i', 'j']]

transposed = zip_longest(*chars)

print(list(transposed))

output will be

[('a', 'c', 'g'), ('b', 'd', 'h'), (None, None, 'i'), (None, None, 'j')]

itertools.accumulate(iterable[, func])

The accumulate() function takes a function as an argument. It also takes an iterable. It returns the accumulated results see example below.

Python Shorcut Example Code8: accumulate()

import itertools
import operator
data = [1, 2, 3, 4, 5]
result = list(itertools.accumulate(data, operator.add))
print(result)

output will be
[1, 3, 6, 10, 15]

Python Shorcut Example Code9: How to Convert List to Comma Separated String?

items1 = ['apple', 'grapes','mango', 'orange']
print(', '.join(items1))
items2 = [1, 2, 3, 4, 5, 6, 7]
print(', '.join(map(str, items2)))
items3 = [1, 'apple', 2, 3, 'grapes', 4, 5, 'dates']
print(', '.join(map(str, items3)))

output will be
apple, grapes, mango, orange
1, 2, 3, 4, 5, 6, 7
1, apple, 2, 3, grapes, 4, 5, dates

Python Shorcut Example Code10: How to Remove Duplicates From List?

lst = [1, 7, 3, 3, 5, 6, 5]
no_dups = list(set(lst))
print(no_dups)

output will be
[1, 3, 5, 6, 7]

Python Shorcut Example Code11: How to Remove Duplicates From List And Also Preserves the List Order?

lst = [1, 7, 3, 3, 5, 6, 5]
from collections import OrderedDict
no_dups = list(OrderedDict.fromkeys(lst).keys())
print(no_dups)

output will be
[1, 7, 3, 5, 6]

Python Shorcut Example Code12: How to Swapping Values?

a, b = 4, 5
a, b = b, a
print(a, b)

output will be
5, 4

Python Shorcut Example Code13: How to Find Index of Min/Max Element?

Code

def min_index(lst):

return min(range(len(lst)), key=lst.__getitem__)

def max_index(lst):

return max(range(len(lst)), key=lst.__getitem__)

lst = [20, 40, 90, 70, 10, 5]

print("min index : {}".format(min_index(lst)))

print("max index : {}".format(max_index(lst)))

output will be

min index : 5
max index : 2