Basic Loops - 'enumerate' and list comprehension


While traditional loops provide powerful control over the flow of code, Python offers advanced looping techniques that let you achieve more with less code. These techniques are not only concise but also enhance code readability.

a. List Comprehensions:

List comprehensions offer a succinct way to create lists based on existing lists or iterables. They can also incorporate conditions to filter out unwanted elements.

Code

squared = [i**2 for i in range(5)]
print(squared)

Output

[0, 1, 4, 9, 16]

b. Using 'enumerate' with Loops:

The 'enumerate' function can be used with loops to retrieve both the index and the value from an iterable simultaneously.

Code

for index, value in enumerate(['a', 'b', 'c']):
    print(index, value)

Output

(0, 'a')
(1, 'b')
(2, 'c')

c. Nested Loops in Comprehensions:

Loops can be nested inside comprehensions to produce more complex results.

Code

pairs = [(x, y) for x in [1,2] for y in [3,4]]
print(pairs)

Output

[(1, 3), (1, 4), (2, 3), (2, 4)]

Enquiries

[email protected]

Copyright © 2023 - slash-root.com