Python - Lists
In Python, you can iterate over elements in a list using a for loop. The loop iterates over each element in the list, allowing you to perform actions on each element one at a time. Here's an example program:
# Creating a list
my_list = [1, 2, 3, 4, 5]
# Iterating over elements in the list using a for loop
for element in my_list:
# Performing an action on each element
print("Element:", element)
The program initializes a list (my_list
) and uses a for loop to iterate over each element in the list. Inside the loop, an action (printing the element) is performed for each iteration.
Output:
Element: 1 Element: 2 Element: 3 Element: 4 Element: 5
Another way to iterate over elements in a list is by using the range()
function and the length of the list. This approach allows you to access elements using their index. Here's an example:
# Creating a list
my_list = [1, 2, 3, 4, 5]
# Iterating over elements in the list using range and length
for i in range(len(my_list)):
# Accessing elements by index and performing an action
print("Element at index", i, ":", my_list[i])
Output:
Element at index 0 : 1 Element at index 1 : 2 Element at index 2 : 3 Element at index 3 : 4 Element at index 4 : 5
zip()
function with lists in Python.The zip()
function in Python is used to combine elements from multiple iterables (e.g., lists) into tuples. It returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the input iterables. Let's explore the use of the zip()
function with lists:
# Creating two lists
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 22]
# Using zip() to combine elements from both lists into tuples
zipped_data = zip(names, ages)
# Displaying the result
for data in zipped_data:
print("Name:", data[0], "| Age:", data[1])
The program creates two lists, names
and ages
, and uses the zip()
function to combine their elements into tuples. The resulting tuples are then iterated over using a for loop, and the elements are displayed.
Output:
Name: Alice | Age: 25 Name: Bob | Age: 30 Name: Charlie | Age: 22