Skip to content
Rezha Julio

Python

Looping techniques in Python

1 min read

Python has multiple techniques for looping over data structures

Python has multiple techniques for looping over data structures.

Dictionary looping with both key and value can be done using the items() method:

my_dict = {'first': 'a', 'second': 'b'}
for k, v in my_dict.items():
print(k, v)
# first a
# second b

The enumerate() function allows looping with both index and value through any sequence:

my_list = ['a', 'b']
for i, v in enumerate(my_list):
print(i, v)
# 0 a
# 1 b

The zip() function can be used to pair two or more sequences in order to loop over both of them in parallel:

first_list = ['a', 'b']
second_list = ['one', 'two']
for f, s in zip(first_list, second_list):
print(f, s)
# a one
# b two

To loop in a sorted order, use the sorted() function:

my_list = ['b', 'c', 'a']
for f in sorted(my_list):
print(f)
# a
# b
# c

To loop in reverse, pass the sorted list to the reversed() function:

for f in reversed(sorted(set(my_list))):
print(f)
# c
# b
# a

Related Posts


Previous Post
Enhance your tuples
Next Post
Keyword argument demystify