Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Python list.extend() Order Presserving?

Tags:

python

list

I'm wondering whether the extend function preserves the order in the two list.

>> list = [1, 2, 3]
>> list.extend([4, 5])
>> list
[1, 2, 3, 4, 5]

Is extend always working like that way?

like image 286
yanzheng Avatar asked Sep 30 '13 02:09

yanzheng


People also ask

Does Python lists preserve order?

Yes, the order of elements in a python list is persistent.

What does extend () do in Python?

The extend() method adds the specified list elements (or any iterable) to the end of the current list.

Does list comprehension preserve order?

Yes, the list comprehension preserves the order of the original iterable (if there is one). If the original iterable is ordered (list, tuple, file, etc.), that's the order you'll get in the result.

Which is faster append or extend?

They take exact same time.


1 Answers

Yes.

list.extend() just extends the arguments given to the end of the list.

According to the docs:

Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.

So:

>>> a = [1, 2, 3]
>>> a[len(a):] = [4, 5]
>>> a
[1, 2, 3, 4, 5]

By the way, don't shadow the built-in type by naming a list list.

like image 183
TerryA Avatar answered Sep 29 '22 13:09

TerryA