📜  ist comperension python (1)

📅  最后修改于: 2023-12-03 14:42:11.201000             🧑  作者: Mango

List Comprehension in Python

List comprehension is a concise and elegant way to create new lists in Python. It allows you to transform, filter, and manipulate elements from an existing list to create a new list in a single line of code.

Syntax

The general syntax of list comprehension is:

new_list = [expression for item in iterable if condition]
  • new_list: The new list that will be created.
  • expression: The expression used to manipulate each element in the original list.
  • item: The variable representing each element in the original list.
  • iterable: The original list or any other iterable objects like strings, tuples, or sets.
  • condition: (Optional) The condition that determines whether an element should be included in the new list.
Examples

Let's see some examples to get a better understanding of list comprehension.

  1. Creating a new list by multiplying each element of an existing list by 2.
numbers = [1, 2, 3, 4, 5]
doubled = [num * 2 for num in numbers]
# doubled: [2, 4, 6, 8, 10]
  1. Generating a list of even numbers from 1 to 10.
evens = [num for num in range(1, 11) if num % 2 == 0]
# evens: [2, 4, 6, 8, 10]
  1. Filtering out vowels from a string.
sentence = "Hello, world!"
consonants = [char for char in sentence if char.lower() not in 'aeiou']
# consonants: ['H', 'l', 'l', ',', ' ', 'w', 'r', 'l', 'd', '!']
  1. Creating a list of squares of numbers divisible by 3 from 0 to 9.
squares = [num ** 2 for num in range(10) if num % 3 == 0]
# squares: [0, 9, 36, 81]

List comprehension can be a powerful tool to simplify your code and make it more readable. It is a commonly used technique in Python programming, and mastering it can greatly enhance your productivity as a programmer.

For more information, refer to the Python documentation on list comprehension.