Using List comprehension we can create a new list from an existing list. Some key elements of Python list comprehension are listed below.
- Shorted syntax
- More time and space efficient than for loops
- Enclosed in square brackets
Syntax:
new_list = [ expression(element) for element in old_list if condition ]
Example:
vehicle = ["bike", "car", "bus"] newlist = [ ] for i in vehicle: if "b" in i: newlist.append(i) print(newlist)
Using list comprehension we can write it in a single line
vehicle = ["bike", "car", "bus"] newlist = [ i for i in vehicle if "b" in i] print(newlist)