[Tutor] Question on List Comprehensions

Charles Karl Becker charleshbecker at gmail.com
Tue Nov 22 00:55:57 CET 2011


I'm trying to use a list comprehension to build a list with a variable
number of lists nested within it (ideally eventually going several
levels of nesting).  However I seem to be observing some strange
behavior and was wondering if anyone could take a look at this and
tell me if what I'm trying to do with list comps is possible, or is a
map() or for loop the best thing here?

I'm not worrying about incrementing the variables in the later
examples since I'm confused about their behavior (just simply adding
new elements to the list rather than nesting the lists; and then
setting the list to [none] in the last uncommented.  The last
commented one produces a syntax error, is it impossible to be
recursive with list comps like that or is my syntax just faulty?)
Thanks!
Charles

Here's the raw code with my comments :

board_size = 5
master_list = []

# this block produces the desired behavior
for c in range(board_size):
    cell = ['', c+1]
    master_list.append(cell)

print(master_list)

# I don't understand why this block behaves the way it does
master_list = []
master_list = [board_size * cell]
print(master_list)

# I also don't understand why this block behaves the way that it does
master_list = []
master_list = [master_list.append(cell)]
print(master_list)

# this block produces a syntax error, and I'm not sure why
'''
master_list = []
master_list = [x for c in range(board_size) master_list.append(cell)]
print(master_list)
'''


More information about the Tutor mailing list