Python From Beginner to Advanced

0% completed

Previous
Next
Python - Looping Through a List

Looping through a list allows you to access each element one by one, making it easy to process and manipulate list data. Python provides multiple ways to iterate over a list, with the most common being the for loop. Other techniques, such as looping with range(), using while, and utilizing enumerate(), provide additional flexibility for handling indexes and conditional operations.

Looping through a list is essential for tasks like data processing, filtering elements, searching values, and performing calculations.

1. Looping Through a List Using a "for" Loop

A for loop directly iterates over the elements of a list, making it the most straightforward way to access each item.

Example 1: Iterating Through a List

Python3
Python3

. . . .

Explanation

  • The for loop iterates through simple_list, assigning each element to fruit one by one.
  • The print() function outputs each fruit on a new line.
  • This method is simple and efficient for iterating over lists of any size.

2. Looping Through a List Using "enumerate()"

The enumerate() function provides an elegant way to loop through a list while keeping track of the index.

Example 2: Using "enumerate()" to Get Index and Value

Python3
Python3

. . . .

Explanation

  • enumerate(names) returns both the index and the value in each iteration.
  • This method is more readable than using range(len(list)).
  • It is useful when both position and value are needed simultaneously.

3. Looping Through a List Using a "while" Loop

A while loop can also be used to iterate through a list, especially when the number of iterations depends on a condition rather than the list size.

Example 3: Iterating Through a List Using "while"

Python3
Python3

. . . .

Explanation

  • The loop continues running as long as index is less than len(numbers).
  • numbers[index] accesses elements based on the current index.
  • index += 1 increments the index in each iteration, preventing an infinite loop.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next