Search code examples
pythonlistloopslist-comprehension

Python Loops and List Comprehension Connection


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


Solution

  • 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]