|
| 1 | +# **List Comprehension** |
| 2 | +A way to create a new list with less syntax can mimic certain lambda functions easier to read. |
| 3 | + |
| 4 | +**Syntax :** |
| 5 | +* `list = [expression for item in iterable]` |
| 6 | +* `list = [expression for item in iterable i conditional]` |
| 7 | +* `list = [expression if/else condition for item in iterable]` |
| 8 | + |
| 9 | +**Example 1:** |
| 10 | +```py |
| 11 | +squares = [] # creates an empty list |
| 12 | +for i in range(1, 11): # creates a for loop |
| 13 | + squares.append(i*i) # defines what each loop iteration should do |
| 14 | +print(squares) |
| 15 | +``` |
| 16 | + |
| 17 | +Now lets use the list comprehension to see the less lines of code. |
| 18 | + |
| 19 | +```py |
| 20 | +squares = [i*i for i in range(1,11)] |
| 21 | +print(squares) |
| 22 | +``` |
| 23 | + |
| 24 | +**Example 2:** |
| 25 | +```py |
| 26 | +# Without List Comprehension |
| 27 | +students = [100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 0] |
| 28 | +passed_students = list(filter(lambda x:x>=60, students)) |
| 29 | +print(passed_students) |
| 30 | + |
| 31 | +# With List Comprehension |
| 32 | +students = [100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 0] |
| 33 | +passed_students = [i for i in students if i >= 60] |
| 34 | +passed_students1 = [i if i >=60 else "FAILED" for i in students] |
| 35 | +print(passed_students) |
| 36 | +``` |
0 commit comments