How to implement Python list comprehension?
List comprehension is a way to simplify code by creating, manipulating, and filtering lists using just one line of code. Its syntax is as follows:
[transform item in iterable if condition]
In this case, the expression is the operation or calculation performed on each item in an iterable, with the condition being an optional filtering criterion.
Here are some common examples of list comprehensions.
- Create a list containing numbers from 1 to 10.
my_list = [x for x in range(1, 11)]
print(my_list) # 输出: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- Square each element in the list.
my_list = [x**2 for x in range(1, 11)]
print(my_list) # 输出: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
- Select the even numbers from the list.
my_list = [x for x in range(1, 11) if x % 2 == 0]
print(my_list) # 输出: [2, 4, 6, 8, 10]
- Convert the case of each string in the list.
my_list = ['apple', 'banana', 'cherry']
new_list = [x.upper() for x in my_list]
print(new_list) # 输出: ['APPLE', 'BANANA', 'CHERRY']
By using list comprehensions, one can easily create, manipulate, and filter lists in a concise manner, enhancing the readability and simplicity of the code.