Python: List Comprehension

List comprehensions are a method for taking a list of elements and performing a transformation on each element.

In our first example, we want to take numbers 0-9, square them, and have the result end up in a list.

ln[5] shows how you would perform this task using for a loop to iterate.

ln[1] does the same thing, but it does it in one line.

 

pythonListcomp

Try your code in our online Python console:  

As you can see, the list comprehension basically crunches the for loop into one line. The syntax is simple enough:

S            =  [x**2 for x in range(10)]

Assign a variable = [operation for loop]

Find even numbers in a list:

Here we add an if statement inside the iteration. (x%2 is modulus, meaning it returns remainder. So 4%2 returns a remainder of 0 and 5%2 returns are remainder of 1)

pythonListcomp1.jpg

You can use list comprehensions with more complex formulas:

pythonListcomp3

You can even use functions from within a list comprehension

pythonListcomp4.jpg

Try your code in our online Python console:  


If you enjoyed this lesson, click LIKE below, or even better, leave me a COMMENT

Last Lesson: Zip and unpack

Next Lesson: Generators

Back to Python Course: Course

 

4 thoughts on “Python: List Comprehension

  1. Cornelius Grieff

    The primary purpose of the day nursery Petersfield is to assist both parents and kids by providing the youngsters the necessary love and
    care and giving the mother and father a way of satisfaction https://math-problem-solver.com/ .
    You’ll be able to see that the estimates ranged from 25 as much as 65.

  2. Pingback: Python zip and unpack – Analytics4All

  3. Pingback: Python: Generators – Analytics4All

Leave a Reply