-1

Sometimes when I look at other posts in stack overflow I see this:

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

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

(I tried looking it up on the docs but I can't find it)

Blue Robin
  • 222
  • 3
  • 13

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
  • 155,156
  • 41
  • 207
  • 295