Aardenon Aardenon - 1 year ago 103
Python Question

Is list.append(x) equivalent to a[len(a):] = [x]

I'm at the very beginning of learning Python 3. Getting to know the language basics. There is a method to the list data type:


and in the tutorial it is said to be equivalent to this expression:

a[len(a):] = [x]

Can someone please explain this expression? I can't grasp the len(a): part. It's a slice right? From the last item to the last? Can't make sense of it.

I'm aware this is very newbie, sorry. I'm determined to learn Python for Blender scripting and the Game Engine, and want to understand well all the constructs.

Answer Source

Think back to how slices work: a[beginning:end]. If you do not supply one of them, then you get all the list from beginning or all the way to end.

What that means is if I ask for a[2:], I will get the list from the index 2 all the way to the end of the list and len(a) is an index right after the last element of the array... so a[len(a):] is basically an empty array positioned right after the last element of the array.

Say you have a = [0,1,2], and you do a[3:] = [3,4,5], what you're telling Python is that right after [0,1,2 and right before ], there should be 3,4,5. Thus a will become [0,1,2,3,4,5] and after that step a[3:] will indeed be equal to [3,4,5] just as you declared.

Edit: as chepner commented, any index greater than or equal to len(a) will work just as well. For instance, a = [0,1,2] and a[42:] = [3,4,5] will also result in a becoming [0,1,2,3,4,5].

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download