Python List Comprehension Syntax
Syntax: newList = [ expression(element) for element in oldList if condition ]
Parameter:
- expression: Represents the operation you want to execute on every item within the iterable.
- element: The term “variable” refers to each value taken from the iterable.
- iterable: specify the sequence of elements you want to iterate through.(e.g., a list, tuple, or string).
- condition: (Optional) A filter helps decide whether or not an element should be added to the new list.
Return:The return value of a list comprehension is a new list containing the modified elements that satisfy the given criteria.
Python List comprehension provides a much more short syntax for creating a new list based on the values of an existing list.
Python – List Comprehension
A Python list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element in the Python list.
Example:
Python
numbers = [ 12 , 13 , 14 ,] doubled = [x * 2 for x in numbers] print (doubled) |
Output
[24, 26, 28]