• 8 December 2024

Python Comprehensions

>>> a  = [ x for x in range(1,20)]
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

>>> b = [ x for x in a if x % 2 == 0 ]
>>> b
[2, 4, 6, 8, 10, 12, 14, 16, 18]

>>> c = [ x*x for x in b if x > 10 ]
>>> c
[144, 196, 256, 324]

>>> [f"ge-0/0/{x}" for x in range(0, 8)]
['ge-0/0/0', 'ge-0/0/1', 'ge-0/0/2', 'ge-0/0/3', 'ge-0/0/4', 'ge-0/0/5', 'ge-0/0/6', 'ge-0/0/7']
>>> my_dict
{'ahmet': 10, 'mehmet': 11, 'samet': 15, 'hasan': 20, 'kadir': 23}
>>>
>>> secmen = { k:v for k,v in my_dict.items() if v > 18 }
>>> secmen
{'hasan': 20, 'kadir': 23}