简体   繁体   中英

Python Loops and List Comprehension Connection

How loops and list comprehension are connected in python? Explain with examples .

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 modifying items in lists

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM