Python list comprehensions

Previous Topic Next Topic
 
Posted by Radishrain Radishrain
Options
https://docs.python.org/3.10/tutorial/datastructures.html

Here's a link where it talks about list comprehensions.

List comprehensions are when you do such as `myList=[v+2 for v in anotherList]`. What this does is make `myList` equal to a new list wherein every item of `anotherList` has been incremented by two.

List comprehensions must be contained within a list, a set, or some such, or Python won't recognize the syntax.

You can replace `anotherList` with such as `range(5)`. However, ranges seem to be special in that the first item of the newly created list will be 0 instead of 2 (if you did `[v+2 for v in range(5)]`; I suppose that's for convenience, since that's probably what people want.

The first part, (where I put `v+2` in the initial example) doesn't actually need to include `v` (it can be something like 55); no, you can't assign values in that place; so, this is invalid: `[v+=2 for v in range(5)]`.

What list comprehensions do is iterate through the loop (`for v in anotherList`) much as usual, and then assign the value placed before it to each iteration (so, `[55 for v in anotherList]` will just replace every value (in the new list) with `55`.

If this whole list comprehension thing seems strange to you, apparently it's very much like something done in mathematics. So, that's probably why they do it like this in Python. However, I found it to be very confusing for many years, personally, and just wished people would write out the full thing. Speaking of that, here's what the full thing looks like (for `myList=[v+2 for v in anotherList]`):

v=0
myList=[]
for v in anotherList:
    myList.append(v+2)
del v #Either that, or the scope of v just ends

Anyway, for me, for a long time, it seemed a rarely enough used feature that when I needed to remember what it did, I had forgotten (and I didn't remember they were called list comprehensions to look them up). However, just about everyone else who programmed in Python did it a lot; so, it was kind of frustrating. I considered it a short way of obfuscating code for programmers of other languages.

Oh, just for the record, you can use strings, and probably other stuff instead of integers:
>>> l=["hello", "Earth is a"]
>>>[s+" world" for s in l]
['hello world', 'Earth is a world']
Feedback, Links, Privacy, Rules, Support