How to create list with List Comprehension
What is List Comprehension
List comprehension is a way of making lists from other lists. It works in a way similar to for loops.
print [x*x for x in range(10)]
The code above generates the following result.
The code above composes x*x for each x in range(10).
The following code prints out squares that are divisible by 3.
print [x*x for x in range(10) if x % 3 == 0]
The code above generates the following result.
We can also create list of tuples.
print [(x, y) for x in range(3) for y in range(3)]
The code above generates the following result.
This can be combined with an if clause.
firstList = ['abc', 'bcd', 'cde']
secondList = ['cde', 'abc', 'bcd']
print [b + ':' + g for b in firstList for g in secondList if b[0] == g[0]]
This gives the pairs of boys and girls who have the same initial letter in their first name.
numbers = [72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33]
print [chr(n) for n in numbers] # characters corresponding to numbers
print [ord(c) for c in 'Hello, world!'] # numbers corresponding to characters
print [n for n in numbers if n % 2 == 0] # filters out the odd numbers
# www. j a v a2 s . c o m
The code above generates the following result.