Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 3b4d25a

Browse files
Create 11_List_Comprehension.MD
1 parent 97fd40a commit 3b4d25a

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

‎Lecture_17/11_List_Comprehension.MD

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /