i faced question confused me lot. meant generate list , reason did like:
mylist = [i in range(5), j j in range(5)] then interpreter complained me that invalid syntax @ position 'j' right before 'for'. define j before list. explain me why did not need define 'i' 'j' ?
i expected like:
[[0,1,2,3,4],[0,1,2,3,4]] however, got (i assign 2 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 confused here, tell me why got outcome?
thanks lot in advance.
what trying create two nested lists, nest comprehensions:
[[i in range(5)], [j j in range(5)]] or, since not doing anything expression, just:
[list(range(5)), list(range(5))] in python 2, list() call redundant.
you did not share 'define j outside list comprehension code' looked like, realize list comprehension supports nested loops.
a list comprehension can seen series of loops , if statements, which, read left right seen nested statements:
[i in range(5) j in range(5)] should read as:
for in range(5): j in range(5): outputlist.append(i) judging output did instead:
[j in range(5)] where j set range(5) on python 2.
Comments
Post a Comment