Loops‎ > ‎

List Comprehension

create new list from elements of another list
newList = [ doSomethingWith(element) for element in oldList ]
newList = [ doSomethingWith(element) for element in oldList if condition ]


Examples

# generate squared numbers from a sequence x = 1...10
[x*x for x in range(1,11)]
  [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

# same, but using a function
def f(x):
    return x*x
y = [f(x) for x in range(1,11)]
  [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]


# converting all strings into int numbers
mylist = ['4', '1', '3', '2']
  ['4', '1', '3', '2']
n = [ int(x) for x in mylist ]
  [4, 1, 3, 2]


# add '1' strings to all strings in a list
mylist = ['A', 'B', 'C']
[ s+'1' for s in mylist ]
  ['A1', 'B1', 'C1']


# adding if condition (get all numbers <3)
mylist=[1,2,3,4]
[ x for x in mylist if x<3 ]
  [1, 2]


# get prefix of all elements in list, cutted at '-' symbol
mylist = ['A-1', 'B-2', 'C-3']
[ s.split('-')[0] for s in mylist ]  # [0] means: take first element after cutting
 ['A', 'B', 'C']