1.11 How to Manipulate Lists with Loops in Python

 In this article, we will explore how to manipulate lists using both for and while loops, including common operations such as iterating through elements, updating list values, and creating new lists based on specific conditions.

1. Iterating Through a List

The most common use of loops with lists is to iterate through all elements. This allows you to perform actions on each element individually.

Example: Using a for Loop

python

# Example list fruits = ["apple", "banana", "cherry"] # Using a for loop to print each fruit for fruit in fruits: print(fruit)

Output:


apple banana cherry

In this example, the for loop goes through each element of the list fruits and prints it.

Example: Using a while Loop

A while loop can also be used to iterate through a list by manually keeping track of the index.

python

fruits = ["apple", "banana", "cherry"] # Initialize index index = 0 # Use a while loop to iterate while index < len(fruits): print(fruits[index]) index += 1

Output:


apple banana cherry

In this case, the loop continues until the index reaches the length of the list, and the current element is accessed via fruits[index].

2. Modifying Elements in a List

You can also modify elements of a list while iterating through it. If you need to update all or some of the elements in a list based on specific criteria, loops make this possible.

Example: Modifying Elements in a List

Let's say we want to multiply all the numbers in a list by 2.

python

numbers = [1, 2, 3, 4, 5] # Using a for loop to modify elements for i in range(len(numbers)): numbers[i] *= 2 # Multiply each number by 2 print(numbers)

Output:

python

[2, 4, 6, 8, 10]

Here, the for loop iterates over the indices of the numbers list, and each element is updated by multiplying it by 2.

3. Filtering a List

Sometimes, you might want to create a new list that contains only certain elements from an existing list based on specific conditions. This can easily be done with a loop.

Example: Filtering a List with a for Loop

Let’s filter out even numbers from a list.

python

numbers = [1, 2, 3, 4, 5, 6, 7, 8] # Create an empty list to store even numbers even_numbers = [] # Use a for loop to filter even numbers for number in numbers: if number % 2 == 0: even_numbers.append(number) print(even_numbers)

Output:

python

[2, 4, 6, 8]

In this example, the loop checks if a number is even (i.e., divisible by 2) and appends it to the even_numbers list.

4. Creating a New List from an Existing List

You can also create a completely new list by applying certain transformations to each element of the original list.

Example: Creating a New List with a for Loop

Let’s say we want to create a new list that contains the squares of all the numbers from an existing list.

python

numbers = [1, 2, 3, 4, 5] # Create an empty list to store squares squares = [] # Use a for loop to calculate square of each number for number in numbers: squares.append(number ** 2) print(squares)

Output:

python

[1, 4, 9, 16, 25]

5. Looping Through a List with enumerate()

Sometimes you need both the index and the element when iterating over a list. Python provides the enumerate() function, which returns both the index and the element simultaneously.

Example: Using enumerate() in a Loop

python

fruits = ["apple", "banana", "cherry"] # Use enumerate to get index and element for index, fruit in enumerate(fruits): print(f"Index {index}: {fruit}")

Output:

python

Index 0: apple Index 1: banana Index 2: cherry

6. Nested Loops with Lists

You can also use nested loops to work with lists, especially if you have a list of lists (also called a nested list).

Example: Iterating Through a Nested List

python

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # Using nested for loops to iterate through a 2D list (matrix) for row in matrix: for element in row: print(element, end=" ") print() # For newline after each row

Output:


1 2 3 4 5 6 7 8 9

In this example, the outer loop iterates through each row of the matrix, and the inner loop iterates through each element of that row.

Previous Post Next Post