Lamian
Lamian

Reputation: 313

how this special python list generated?

I just faced to a question that confused me a lot. I meant to generate a list and for some reason I did something like:

mylist = [i for i in range(5), j for j in range(5)]

Then interpreter complained to me that that is invalid syntax at the position 'j' right before 'for'. So I define j before the list. Could anybody explain me why I did not need to define 'i' but 'j' ?

I expected to get something like:

[[0,1,2,3,4],[0,1,2,3,4]]

However, I got (I assign 2 to j in advance)

[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], 2, 2, 2, 2, 2]

I really confused here, could anyone tell me why I got this outcome?

Thanks a lot in advance.

Upvotes: 0

Views: 113

Answers (3)

dansalmo
dansalmo

Reputation: 11696

To create what you wanted you can just do:

>>> [range(5)]*2
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]

or, if you need the lists to be separate objects as pointed out by @Blckknght:

>>> [range(5), range(5)]
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]

Upvotes: 0

joente
joente

Reputation: 856

You want to create two lists inside a list so:

list_ = [list(range(5)), list(range(5))]
print(list_) # [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]

It's not a good idea to overwrite the 'list' buildin, so it's better to add a underscore to the list name or use another name.

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1123360

What you are trying to do is create two nested lists, so nest your comprehensions:

[[i for i in range(5)], [j for j in range(5)]]

or, since you are not doing anything with the expression, just:

[list(range(5)), list(range(5))]

In Python 2, even the list() call is redundant.

You did not share what your 'define j outside the list comprehension code' looked like, but do realize that a list comprehension supports nested for loops.

A list comprehension can be seen as a series of for loops and if statements, which, read from left to right are seen as nested statements:

[i for i in range(5) for j in range(5)]

should be read as:

for i in range(5):
    for j in range(5):
        outputlist.append(i)

Judging from your output you did something like this instead:

[j for i in range(5)]

where j was set to range(5) on Python 2.

Upvotes: 6

Related Questions