How to Perform an Operation on Each Element of a List in Python?

Estimated read time 2 min read

To perform an operation on each element of a list in Python, you can use a for loop or a list comprehension. Here are examples of each approach:

Using a for loop:

numbers = [2, 4, 6, 8, 10]
squares = []
for number in numbers:
    square = number ** 2
    squares.append(square)
print(squares)

In this example, the numbers list contains five elements. The for loop iterates over each element of the list and calculates the square of each number using the exponent operator (**). The result of each calculation is appended to a new list called squares. Finally, the print statement outputs the contents of the squares list to the console.

Using a list comprehension:

numbers = [2, 4, 6, 8, 10]
squares = [number ** 2 for number in numbers]
print(squares)

In this example, the list comprehension performs the same calculation as the for loop example, but in a more concise way. The list comprehension creates a new list called squares that contains the square of each element in the numbers list. The syntax of a list comprehension is expression for item in iterable, where expression is the operation to be performed on each element of the iterable (in this case, calculating the square), item is a variable that represents each element in the iterable (in this case, each number in the numbers list), and iterable is the object to be iterated over (in this case, the numbers list). Finally, the print statement outputs the contents of the squares list to the console.

Both the for loop and list comprehension approaches are useful for performing operations on each element of a list in Python, and which one to use depends on personal preference and the specific use case.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply