How loops and list comprehension are connected in python? Explain with examples.
Asked
Active
Viewed 60 times
1 Answers
1
Here a documentation about List Comprehensions and Loops
Loops are used for iterating through Lists, Tuples and other Iterables
items = [1, 3, 6]
for item in items:
print(item)
> 1
> 3
> 6
List Comprehensions are used for creating new lists from another Iterable
items = [1, 3, 6]
double_items = [item * 2 for item in items]
print(double_items)
> [2, 6, 12]
You can also filter items with List Comprehensions like this
items = [1, 3, 6, 8]
even_items = [item for item in items if item % 2 == 0]
print(even_items)
> [6, 8]

Yevhen Bondar
- 4,357
- 1
- 11
- 31
-
"List Comprehensions are used for modifying items in lists" no, list comprehensions are for *creating new lists* – juanpa.arrivillaga Dec 26 '21 at 11:57
-
@juanpa.arrivillaga nice point, updated the answer – Yevhen Bondar Dec 26 '21 at 12:16