 # The logic behind list comprehensions?

Hello!

I have been working a lot with list comprehensions lately, but I still don’t really ‘get’ what exactly is going on when I use them. That is, what is the syntax `operation_on_i for i in some_list` really asking python to do and how does python understand what I am asking it?

Thanks!

I figured it was [make a list] for i in [source list]

edit: well, I guess that’s not right either, since I was just making lists of None in my class.

some_list = [None for i in range(integer)]

Hi Taylor.

Well, the way I understand List Comprehensions is a simpler way to create a list based on another list.

original_list = [ 1 , 2 , 3 , 4 , 5 ]

You want another list that take each value of the original_list and multiply it by 2. So you want:

original_times_two = [ 2 , 4 , 6 , 8 , 10 ]

There are many ways to get this result. Using Loops is the most basic one. But List Comprehension is much simpler.

So, thinking about the sintax you mentioned, let’s break it into pieces:

operation_on_i for i in some_list

some_list is the original_list. Is the list that you are using the values.
i is a temporary variable. The for will make i assume each value of the original_list, one at a time.
operation_on_i is basically what you want to do with each value assumed by i

All of that goes inside the list you want to create.

Getting back to my example, this is what you should do:

original_times_two = [ i * 2 for i in original_list ]

I hope I helped and I am sorry if it was a bit confusing. If you need anything else, just ask.

3 Likes

Thank you! Your explanation was very clear. I appreciate the help!

2 Likes

@m.cassani’s explanation lays it out nicely, I felt it’s worth adding that there’s nothing restricting the you to iterate through a list, any iterable could be used (for example you’ll commonly see `range` used in the lessons but there are many more options).

1 Like

Ah, good point @tgrtim. Thanks for pointing this out!