List Comprehension
What You'll Learn: In this tutorial, you'll discover how to create a new list based on the values of an existing list using list comprehension. It's a shorter and more readable way to handle lists!
What is List Comprehension?
List comprehension offers a compact way to create lists. It can make your code cleaner and easier to read.
Example: Filtering Fruits
Imagine you have a list of fruits and you want to create a new list with only the fruits that have the letter "a" in their names.
Without List Comprehension:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)Output: ["apple", "banana", "mango"]
With List Comprehension:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)Output: ["apple", "banana", "mango"]
Syntax of List Comprehension
newlist = [expression for item in iterable if condition]
expression: The current item in the iteration, which is the outcome.item: The current item in the iterable.iterable: An object like a list, tuple, set, etc.condition(optional): A filter that only accepts items that evaluate to True.
Examples
Filter Items:
- Only accept items that are not "apple".
pythonfruits = ["apple", "banana", "cherry", "kiwi", "mango"] newlist = [x for x in fruits if x != "apple"] print(newlist)Output:
['banana', 'cherry', 'kiwi', 'mango']
Iterable Example:
- Use the
range()function to create an iterable.
pythonnewlist = [x for x in range(10)]Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
- Use the
Condition Example:
- Accept only numbers lower than 5.
pythonnewlist = [x for x in range(10) if x < 5]Output:
[0, 1, 2, 3, 4]
Manipulate Outcome:
- Set the values in the new list to upper case.
pythonnewlist = [x.upper() for x in fruits]Output:
['APPLE', 'BANANA', 'CHERRY', 'KIWI', 'MANGO']
- Set all values in the new list to 'hello'.
pythonnewlist = ['hello' for x in fruits]Output:
['hello', 'hello', 'hello', 'hello', 'hello']
Conditional Expression:
- Return "orange" instead of "banana".
pythonnewlist = [x if x != "banana" else "orange" for x in fruits]Output:
['apple', 'orange', 'cherry', 'kiwi', 'mango']
Try It Yourself: Fun Exercises
- Filter Your Favorite Colors:
- Create a list of colors.
- Use list comprehension to create a new list with colors containing the letter "e".
- Number Manipulation:
- Create a list of numbers from 1 to 20.
- Use list comprehension to create a new list with only even numbers.
Summary:
In this Python tutorial, we learned how to use list comprehension to create new lists based on existing ones. This method offers a concise and readable way to filter and manipulate list items. Keep experimenting and have fun with list comprehension in Python!