Looping Techniques in Python (original) (raw)

Last Updated : 12 Jan, 2026

Python provides multiple looping techniques that help iterate over containers like lists, tuples, sets, and dictionaries. These techniques are efficient, save memory and reduce coding effort compared to traditional for and while loops.

Using enumerate()

enumerate() function allows you to loop through a container while getting both the index and the value.

Python `

words = ['The', 'Big', 'Bang', 'Theory']

for index, value in enumerate(words): print(index, value)

`

Output

0 The 1 Big 2 Bang 3 Theory

**Explanation:

Using zip()

zip() function combines two or more containers and iterates over them in parallel. The loop stops at the length of the shortest container.

Python `

names = ['Leo', 'Kendall', 'Harry'] ages = (24, 27, 25)

for name, age in zip(names, ages): print(f"Name: {name}, Age: {age}")

`

Output

Name: Leo, Age: 24 Name: Kendall, Age: 27 Name: Harry, Age: 25

**Explanation:

Using items()

items() allows you to loop through a dictionary and access both its keys and values simultaneously.

Python `

p1 = {'Washington': 'First', 'Lincoln': 'Emancipator', 'Roosevelt': 'Trust-Buster'}

for name, title in p1.items(): print(name, title)

`

Output

Washington First Lincoln Emancipator Roosevelt Trust-Buster

**Explanation: **for name, title in p1.items(): Loops through the dictionary, giving access to each key (name) and value (title).

Using sorted()

sorted() iterates over the list in ascending order without changing the original list.

Python `

num = [1, 3, 5, 6, 2, 1, 3]

print("Sorted list:") for n in sorted(num): print(n, end=" ")

print("\nSorted list without duplicates:") for n in sorted(set(num)): print(n, end=" ")

`

Output

Sorted list: 1 1 2 3 3 5 6 Sorted list without duplicates: 1 2 3 5 6

**Explanation:

Using reversed()

reversed() iterates over a container in reverse order without modifying it.

Python `

num = [1, 3, 5, 6, 2, 1, 3]

for n in reversed(num): print(n, end=" ")

`

**Explanation: for n in reversed(num): Loops through the list in reverse order without changing the original list.

While Loop with If Condition

while loops are useful when you need conditional iteration.

Python `

count = 0

while count < 5: if count == 3: print("Count is 3") count += 1

`

**Explanation: