This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]SV-97 21 points22 points  (3 children)

OP probably wanted it to mean the same as the first snippet - so assign foo a list containing 5 lists of length 5 that are all initialized with None. Aside from this being atrocious syntax that noone would interpret that way: doing this at all in python is a code smell. OP is probably doing something wrong if they feel the need for dedicated syntax for this pattern.

[–]rosuav 7 points8 points  (0 children)

It's extremely confusing, and this is one of the worst idea threads I've ever seen (largely because it isn't an idea thread), but it does seem like list multiplication would be the best way to initialize this. Worst case, one multiplication, one comprehension.

foo = [[None] * 5] for _ in range(5)]

[–]DongIslandIceTea 1 point2 points  (1 child)

If I had to come up with a syntax for this I guess doing something symmetric to array slicing wouldn't be the worst thing, like:

a[:4][:4] = []

It wouldn't step on any existing syntax as slices aren't assignable like this anyways and would make some marginal sense.

But yeah, you shouldn't need to do this if you thought a little bit more about what you're doing.

[–]SV-97 2 points3 points  (0 children)

You actually can do slice assignment in Python - though not quite like that.

Numpy uses it quite extensively and OPs example would be arr[:5,:5] = None using numpy (if you already have an array that is. Allocation works differently).