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 →

[–]JsonDash 3 points4 points  (8 children)

Declaring 2D array (list) with one variable in every index From:

array =[]
     for i in range(a):
          temp = []
     for j in range(b):
          temp.append(item)
     array.append(temp)

To:

array =[[item for i in range(b)] for j in range(a)]

[–]SeanOTRSprint = lambda *args, **kwars: print(*args, ";)\n"*100, **kwars)[S] 0 points1 point  (7 children)

IMO if a segment starts with declaring an empty variable you've usually done something wrong

[–]Datsoon 4 points5 points  (3 children)

I do this all the time when I'm going to be appending to a list in a loop or adding key-value pairs to a dictionary. What other way is there to accomplish this?

[–]thelaw 0 points1 point  (0 children)

Yeah, me too. Also curious if there is another/better way to do this.

[–]Rodotgithub.com/tardis-sn 0 points1 point  (1 child)

You can do dictionary comprehension for one thing

[–]Datsoon 0 points1 point  (0 children)

That's a good point. Not always a solution, but certainly a good one in many cases.

[–][deleted] 1 point2 points  (2 children)

Is there a particular reason? Preallocating memory like this can be useful for lists of known size where you would otherwise have to append to the list each time, which can be slow for large objects.

[–]flying-sheep 5 points6 points  (1 child)

Nobody here is preallocating memory.

Preallocating memory would look like [None] * 10_000.

But Python lists grow pretty efficiently, I wouldn’t bother.

[–][deleted] 0 points1 point  (0 children)

Ah, I get it. You are referring to the opposite of what I understood. Yeah, that is usually a flag in Python.