Skip to content

Commit 70274dd

Browse files
authored
Update list-comprehension.md
Added information to list-comprehension.md
1 parent 09b2ef1 commit 70274dd

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

basics/list-comprehension.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,55 @@
1+
# List Comprehension
2+
3+
4+
## Definition
5+
List comprehensions creates a new list from an existing list that is a shorter syntax than normal. It also processes the list much faster than using a for loop.
6+
7+
8+
## Without List Comprehension
9+
```python
10+
animals = ["dog", "cat", "giraffe", "donkey", "ape"]
11+
arr = []
12+
13+
for i in animals:
14+
if len(i) == 3:
15+
arr.append(i)
16+
17+
print(arr)
18+
```
19+
```python
20+
['dog', 'cat', 'ape']
21+
```
22+
The example above shows a list of animals and the for loop iterates through the list of animals and the if statement filters the list and only adds the animal if their name is exactly 3 characters long.
23+
24+
## With List Comprehension
25+
```
26+
animals = ["dog", "cat", "giraffe", "donkey", "ape"]
27+
28+
arr = [i for i in animals if len(i) == 3]
29+
print(arr)
30+
```
31+
```python
32+
['dog', 'cat', 'ape']
33+
```
34+
The example above does exactly the same thing but is in a much more concise syntax where it iterates through the list of animals and appends to the new list if their name is exactly 3 characters long.
35+
36+
## Syntax
37+
38+
newlist = [**expression** for **item** in **iterable** if **condition**]
39+
This is the usual form in which list comprehension is used.
40+
41+
**Expression:** It is the current item for each iteration but also serves as the outcome which can be manipulated before it becomes added to the new list.
42+
```python
43+
animals = ["DOG", "CAT", "GIRAFFE", "DONKEY", "APE"]
44+
45+
arr = [i.lower() for i in animals if len(i) == 3]
46+
print(arr)
47+
```
48+
```python
49+
['dog', 'cat', 'ape']
50+
```
51+
The **i** is essentially an animal each iteration where it checks if the animal's name is 3 characters long and if it does it **also** changes that animal name to all lower case before it finally appends or adds it to the list.
52+
53+
54+
155

0 commit comments

Comments
 (0)