-1

How does the for loop work in lists? Where can I find the documentation for this?

Sometimes when I look at other posts on Stack Overflow I see this:

my_list = [x.split(",") for x in my_list]

(I tried looking it up on the documentation, but I couldn’t find it.)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

1 Answers1

1

It's called List Comprehensions and it is basically a quick way to build a sequence. The code you demonstrate basically means,

for each x in my_list, perform x.split(","), and then put all the result in a new list, which is then passed to my_list.

It is equivalent to:

new_list = []

for x in my_list:
    y = x.split(",")
    new_list.append(y)

my_list = new_list

So you can see with list comprehensions it is a lot simpler.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303