

#Python list comprehension code#
Then the code creates an empty list called Result. The first list runs from one to 10, and the second list runs from 11 to 20. Squares = Ĭreates the input data set and stores it in Numbers. You could write the following code using a single list comprehension: Numbers = ,

Say you have two lists of numbers and you want to return the square of all of the even numbers.

This becomes useful when you have a list of lists (instead of merely a single list). It’s a way to combine not only one, but multiple for loops, if statements and functions into a single line of code. Now let’s dive in to nested list comprehensions.Ī nested list comprehension doubles down on the concept of list comprehensions. įor a more detailed discussion of how those two pieces of code return the same result see my guide to list comprehensions. Those two print statements will show the exact same result. Here’s an example showing how list comprehensions work: Numbers = It applies a for loop, if statement and a function all in a single line. That code sorts through each value in your data set, checks to see if it meets the condition, applies the stated function and stores it in a list named Result. Quick Refresher: What Is a List Comprehension?Īs a quick refresher, a list comprehension is a way to create a new list by filtering elements in a list that meet a condition, transforming the elements as desired and storing the new values in a list. This creates a nested list comprehension and further simplifies your code.īack to Basics Increase the Readability of Your Python Script With 1 Simple Tool You can place one list comprehensions within another list comprehension. List comprehensions create a new list by scanning all items in a list, checking to see if they meet a condition, passing the values that do and applying a function to them.
