Home

list comprehensions

Mit list comprehensions ist es Möglich einfache for-loops als Einzeiler zu schreiben. Die erzeugte Liste wird im Speicher gehalten. Aus 3 wesentlichesn Komponenten besteht eine list comprehensions:

  • Iterable
  • Iterator Variable
  • Ausgabe Anweisung

Basic:
[output expression for iterator variable in iterable]

Advanced:
[output expression + condition for iterator variable in iterable + condition]

for - loop

In [6]:
nums = [4,7,22,9]
numsPlusOne = []
for num in nums:
    numsPlusOne.append(num + 1)
print(numsPlusOne)
[5, 8, 23, 10]

for - loop in list comprehensions style

In [17]:
nums = [4,7,22,9]
numsPlusOne = [num + 1 for num in nums]
print(numsPlusOne)
[5, 8, 23, 10]

nested list comprehensions

In [26]:
matrix = [[col + row for col in range(5)] for row in range (5)]
for row in matrix:
    print(row)
[0, 1, 2, 3, 4]
[1, 2, 3, 4, 5]
[2, 3, 4, 5, 6]
[3, 4, 5, 6, 7]
[4, 5, 6, 7, 8]

conditionals in comprehensions

In [30]:
mylist = [num for num in range(10) if num % 2 ==0]
print(mylist)
[0, 2, 4, 6, 8]

conditionals in comprehensions on the output expression

In [37]:
mylist = [num if num % 2 == 0 else '-' for num in range(10)]
print(mylist)
[0, '-', 2, '-', 4, '-', 6, '-', 8, '-']

list comprehensions for list of tuples

In [67]:
myListOfTuples = [('A1','A2','A3'),('B1','B2','B3')]
newList = [val1 + val2 + val3 for val1,val2,val3 in myListOfTuples]
print(newList)
newList = [tup[0] + tup[1] + tup[2] for tup in myListOfTuples]
print(newList)
['A1A2A3', 'B1B2B3']
['A1A2A3', 'B1B2B3']

dict comprehensions

In [40]:
myDict  = {key: key * 2 for key in range(10)}
print(myDict)
{0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}

generators

Sehr ähnlich wie list comprehensions jedoch mit () statt [].
Die erzeugte Liste wird jedoch nicht komplett im Speicher gehalten. Sondern erst für jede einzelne Iteration on the fly generiert.

In [48]:
myGenerator = (len(val) for val in ['a','aa','aaa'])
print(myGenerator)
print(list(myGenerator))
<generator object <genexpr> at 0x1113d7550>
[1, 2, 3]

generator function

In [53]:
my_list = ['a','aa','aaa']
def get_lengths(input_list):
    for value in input_list:
        yield len(value)

print(get_lengths(my_list))
print(list(get_lengths(my_list)))
<generator object get_lengths at 0x1113d7d50>
[1, 2, 3]
Impressum