📜  python list Comprehensions - Python (1)

📅  最后修改于: 2023-12-03 15:34:02.090000             🧑  作者: Mango

Python List Comprehensions

Python List Comprehensions is a concise way to create lists based on existing lists.

Syntax
new_list = [expression for item in iterable if condition]
  • expression: The expression is the result of operations performed on the item in the iterable. This expression is what will be added to the new list.
  • item: This is the element in the iterable that will be used in the expression and added to the new list.
  • iterable: This is the list, set, sequence, or any other iterable object that will be used to create the new list.
  • condition: This is an optional parameter that will filter item before adding it to the new list.
Examples:
Basic list comprehension
numbers = [1, 2, 3, 4, 5]
squares = [num ** 2 for num in numbers]
print(squares)

Output:

[1, 4, 9, 16, 25]
List comprehension with if condition
fruits = ['apple', 'banana', 'cherry', 'kiwi', 'mango']
new_list = [fruit for fruit in fruits if 'a' in fruit]
print(new_list)

Output:

['apple', 'banana', 'mango']
List comprehension with if-else condition
numbers = [1, 2, 3, 4, 5]
new_list = [num if num % 2 == 0 else 'odd' for num in numbers]
print(new_list)

Output:

['odd', 2, 'odd', 4, 'odd']
Nested list comprehension
matrix = [[1, 2], [3, 4], [5, 6], [7, 8]]
flattened_matrix = [num for row in matrix for num in row]
print(flattened_matrix)

Output:

[1, 2, 3, 4, 5, 6, 7, 8]

List comprehensions are a powerful and concise way to create new lists with specific criteria. They can be used in situations where filtering or mapping is required, and can be nested for more complex operations. Try experimenting with them in your own code to see how they can make your code more streamlined and readable.