Python - List Comprehension
Python - List Comprehension
Dark mode
Dark code
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP BOOTSTRAP HOW TO W3.CSS C C++ C# REACT R JQUERY DJANGO
Python Tutorial
Python HOME ADVERTISEMENT
Python Intro
Python Get Started
Python Syntax
Python Comments
Python Variables
Python Data Types
Python - List Comprehension
Python Numbers
❮ Previous Next ❯
Python Casting
Python Strings
Python Booleans
Python Operators List Comprehension
Python Lists
Python Lists List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.
Loop Lists
List Comprehension
Example Get your own Python Server
Sort Lists
Copy Lists fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
Join Lists newlist = []
List Methods
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
Try it Yourself »
With list comprehension you can do all that with only one line of code:
Example
COLOR PICKER
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
print(newlist)
Try it Yourself »
ADVERTISEMENT
The Syntax
newlist = [expression for item in iterable if condition == True]
The return value is a new list, leaving the old list unchanged.
Condition
The condition is like a filter that only accepts the items that valuate to True . ADVERTISEMENT
Example
Only accept items that are not "apple":
Try it Yourself »
The condition if x != "apple" will return True for all elements other than "apple", making the new list contain all fruits except
"apple".
Example
With no if statement:
Try it Yourself »
Iterable
The iterable can be any iterable object, like a list, tuple, set etc.
Example
You can use the range() function to create an iterable:
Try it Yourself »
Example
Accept only numbers lower than 5:
Try it Yourself »
Expression
The expression is the current item in the iteration, but it is also the outcome, which you can manipulate before it ends up like a
list item in the new list:
Example
Set the values in the new list to upper case:
Try it Yourself »
Example
Set all values in the new list to 'hello':
Try it Yourself »
The expression can also contain conditions, not like a filter, but as a way to manipulate the outcome:
Example
Return "orange" instead of "banana":
Try it Yourself »
ADVERTISEMENT
ADVERTISEMENT
FORUM | ABOUT
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we
cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.