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.
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.
squared = [i**2 for i in range(5)] print(squared)
[0, 1, 4, 9, 16]
The 'enumerate' function can be used with loops to retrieve both the index and the value from an iterable simultaneously.
for index, value in enumerate(['a', 'b', 'c']): print(index, value)
(0, 'a') (1, 'b') (2, 'c')
Loops can be nested inside comprehensions to produce more complex results.
pairs = [(x, y) for x in [1,2] for y in [3,4]] print(pairs)
[(1, 3), (1, 4), (2, 3), (2, 4)]
Copyright © 2023 - slash-root.com