Python List Comprehensions

List comprehensions are an alternative to using for loops and lambda functions (next section). They are an elegant and concise way to define and create lists based on existing list or string. The syntax of a list comprehension Is as follows:

Lets say you have a list of sequential numbers from 0 to 10 and you wanted to create a new list that has all the numbers in the original list with +5 added to each item.

You could use a for loop for this purpose:

You could also use a list comprehension.

1) Create a List Comprehension

List comprehensions process faster and are more concise.

2) Create a list using a List comprehension that has a filter

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response