Reputation: 415
It is allowed the use of a comprehension list on a "list of lists"? I would like to extract a list from a nested list. I did try this:
def main():
a = ['1','2','3']
b = ['4','5','6']
c = ['7','8','9']
board = [a,b,c]
y = [x for x in board[1][i] if i in range(0,3)]
print y
but I get "NameError: name 'i' is not defined". I'm using the wrong syntax or nested list cannot be used like this?
Thanks a lot!
Upvotes: 0
Views: 210
Reputation: 1124788
Nesting loops in list comprehensions work the same way as nesting regular for loops, one inside the other:
y = [x for i in range(3) for x in board[1][i]]
but in this case, just selecting board[1][:]
would be easier and give you the same result; a copy of the middle row.
If you need to apply an expression to each column in that row, then just loop over board[1]
directly:
y = [foobar(c) for c in board[1]]
Upvotes: 2