Extending a list in #Python

>>> a = []
>>> a.extend([2, 1]) # neat
>>> a += [3, 4] # hmm ok
>>> a += (7, 11) # huh?
>>> a[-1:] += [18, 29] # uh oh
>>> a[:] = [*a, 47, 76] # 😦
>>> a
[2, 1, 3, 4, 7, 11, 18, 29, 47, 76]

#pythonoddity

Follow

@treyhunner "There should be one– and preferably only one –obvious way to do it." -The Zen of Python

@peterdrake Exactly what I had in mind when sharing that. 😜

Though in this case I'd say there's approximately two obvious ways to do it.

a.extend([2, 1])

And

a += [2, 1]

Which I use depends on what the surrounding code looks like and the whim of the moment. 🤷

Sign in to participate in the conversation
CleverLibre Social

CleverLibre Social is an inclusive social instance for open discussion, learning, and community.
All cultures welcome.
Hate speech and harassment strictly forbidden.