More Related Content
Similar to Python Programming Essentials - M34 - List Comprehensions (20)
More from P3 InfoTech Solutions Pvt. Ltd. (18)
Python Programming Essentials - M34 - List Comprehensions
- 3. © SkillBrew http://skillbrew.com
Introduction
Lets say you are given a list and your task is to generate
another list of cubes
sample = [10, 20, 30, 40]
cubes = []
for x in sample:
cubes.append(x**3)
print cubes
Output:
[1000, 8000, 27000, 64000]
3
- 4. © SkillBrew http://skillbrew.com
Lets write a List comprehension
sample = [10, 20, 30, 40]
cubes = [ x**3 for x in sample_list]
print cubes
Output:
[1000, 8000, 27000, 64000]
4
sample = [10, 20, 30, 40]
cubes = []
for x in sample:
cubes.append(x**3)
vs
- 6. © SkillBrew http://skillbrew.com
Filter
Lets tweak the problem a little. Generate a list of cubes but
do the operation only on elements that are even.
sample = [10, 21, 33, 40]
cubes = [ x**3 for x in sample if x%2 == 0 ]
print cubes
Output:
[1000, 64000]
6
- 7. © SkillBrew http://skillbrew.com
Nested for loops
Lets say you have a 3 3 Matrix and you have to print
out all the coordinate pairs
0 1 2
0 (0,0) (0, 1) (0, 2)
1 (1,0) (1, 1) (1, 2)
2 (2,0) (2, 1) (2, 2)
7
- 8. © SkillBrew http://skillbrew.com
Naive way
matrix = []
for x in range(3):
for y in range(3):
matrix.append((x,y))
print matrix
Output:
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1),
(1, 2), (2, 0), (2, 1), (2, 2)]
8
- 9. © SkillBrew http://skillbrew.com
With List comprehensions
matrix = [(x,y) for x in range(3) for y in
range(3)]
print matrix
Output:
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1,
2), (2, 0), (2, 1), (2, 2)]
9