0

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!

1
  • What do you expect the output to be? Commented Apr 3, 2013 at 14:53

1 Answer 1

2

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]]
Sign up to request clarification or add additional context in comments.

1 Comment

The comprehension list allows me to select a column too, not only a row. There is a faster way to return a column like you did with "board[1][:]" for the row? Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.