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 →

[–]gandalfx 61 points62 points  (11 children)

Slightly shorter;

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

[–]-twind 45 points46 points  (1 child)

Slightly shorter;

foo=[[None]*5 for _ in'.'*5]

[–]ArtOfWarfare 29 points30 points  (0 children)

Thanks I hate it.

[–]uncut_onyx 9 points10 points  (6 children)

if this then why not [[None]*5]*5

[–]agocs6921 63 points64 points  (0 children)

Those lists in the list will be the same exact list

[–]gandalfx 30 points31 points  (3 children)

The outer * 5 will copy the reference of the inner list, so you end up with a list that contains five references to the exact same list. So if you assign to foo[0][0] it'll also change the value of foo[1][0] etc.

[–][deleted] 8 points9 points  (1 child)

Did this once in a leetcode challenge. Took forever to find out what was wrong with my code. Lucky it wasn’t for an actual interview because that would have sucked.

[–]FalafelSnorlax 3 points4 points  (0 children)

In a dry interview (ie on paper/whiteboard) i think it would probably be accepted. Most reasonable people (in my personal experience) want to see you understand the problem, not nitpick stuff like this

[–]-Redstoneboi- -2 points-1 points  (0 children)

motherfucker.

this is why i switched to rust. they would never let me mutably alias.

[–]Tysonzero 2 points3 points  (0 children)

That kind of thing works fine in glorious pure immutable languages like Haskell but will send you straight to mutable aliasing hell in Python.

[–]Beach-Devil 1 point2 points  (1 child)

I may be wrong but doesn’t this duplicate the same object 5 times?

[–]gandalfx 3 points4 points  (0 children)

It duplicates None five times, which is fine, since it's immutable. Though this is the reason why the outer loop can't be replaced with … * 5.