The ol' [[]] * 500 bug...

K

kj

....just bit me in the "fuzzy posterior". The best I can come up with
is the hideous

lol = [[] for _ in xrange(500)]

Is there something better? What did one do before comprehensions
were available? I suppose in that case one would have to go all
the way with

lol = [None] * 500
for i in xrange(len(lol)):
lol = []

Yikes. 10 miles uphill, both ways...

kynn
 
J

Jon Clements

...just bit me in the "fuzzy posterior".  The best I can come up with
is the hideous

  lol = [[] for _ in xrange(500)]

Is there something better?  

That's generally the accepted way of creating a LOL.
What did one do before comprehensions
were available?  I suppose in that case one would have to go all
the way with

  lol = [None] * 500
  for i in xrange(len(lol)):
      lol = []

Yikes.  10 miles uphill, both ways...
lol = map(lambda L: [], xrange(5))
[id(i) for i in lol]

[167614956, 167605004, 167738060, 167737996, 167613036]

Jon.
 
D

Diez B. Roggisch

kj said:
...just bit me in the "fuzzy posterior". The best I can come up with
is the hideous

lol = [[] for _ in xrange(500)]

If you call that hideous, I suggest you perform the same exercise in
Java or C++ - and then come back to python and relax....


Diez
 
U

Ulrich Eckhardt

Diez said:
kj said:
lol = [[] for _ in xrange(500)]

If you call that hideous, I suggest you perform the same exercise in
Java or C++ - and then come back to python and relax....

I might be missing something that's not explicitly mentioned here, but I'd
say that all non-associative containers in C++ have a resize() method, some
even taking an initial size in their constructor.

That said, [[]]*500 is IMHO more readable.

Uli
 
S

Steven D'Aprano

...just bit me in the "fuzzy posterior".

It's not a bug. Just because it doesn't behave as you would like it to
behave doesn't mean it isn't behaving as designed.

The best I can come up with is the hideous

lol = [[] for _ in xrange(500)]

That's not hideous.

Is there something better? What did one do before comprehensions were
available? I suppose in that case one would have to go all the way with

lol = [None] * 500
for i in xrange(len(lol)):
lol = []

Yikes. 10 miles uphill, both ways...


What's wrong with that?


lol = []
for _ in xrange(500): lol.append([])


is a simple alternative too, although the list comp is better.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top