3 ms·
x = [0] * 100
by Goladus 15y ago
x = [0] * 100
- zmmmmm 15y agoThanks! At first I wondered about efficiency but it seems like I can allocate lists with tens of millions of elements this way without any spike in CPU so it is obviously implemented efficiently. I knew there would be a better way :-)
- Ixiaus 15y agoThis is much better than my own comment - I never even knew about that syntax! Is it efficient though?
- Goladus 15y agoMy guess is that it's optimized, but I don't know. Semantics-wise, it's consistent with list addition. >>> [0] + [0] + [0] [0, 0, 0] >>> [0] * 3 [0, 0, 0]
- Ixiaus 15y agoI just read, that syntax is sugar for the list.extend() method so it's still making copies of the list - I wouldn't use it for a list containing complex objects; but that is very idiomatic for simple use cases (like this one?).
- calpaterson 15y agoIt isn't syntax - help(list.__mul__)
- daeken 15y agoJust make sure that when you do this, you're not initializing it with mutable objects, e.g. lists. x = [[0]] * 2 print x[0], x[1] # prints [0] [0] x[0].append(1) print x[0], x[1] # prints [0, 1] [0, 1] That's because the objects inside the repeated list are simply references to the same object internally.
- deleted 15y ago[deleted]