ob-vaults/Phoenix/Python/Python List Comprehension.md
2024-09-12 17:54:01 +03:30

1.1 KiB

status: #doc Tags: : #python #programming links:python Date: 2023-05-04


Python List Comprehension

syntax

new_list = [expression for item in iterable if condition]
  • expression : what to do to item from iterable for example if in list of [1,2,3] we have x as item if we do x*2 the list we get is [2,4,6]
  • item : for every iteration on iterable (list,string,...) we get one item so here we name it
  • iterable (list,string,...)
  • condition : an if statement that look at the item if it get true it send it to expression for handling and its optional

Here's an example that demonstrates how to use a list comprehension to create a new list of even numbers from an existing list:


# create a list of numbers 
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
# use a list comprehension to create a new list of even numbers 
even_numbers = [x for x in numbers if x % 2 == 0]
# print the new list
print(even_numbers)

---> output

[2, 4, 6, 8, 10]

References

https://www.programiz.com/python-programming/list-comprehension https://peps.python.org/pep-0202/