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?
Yes, the order of elements in a python list is persistent.
The extend() method adds the specified list elements (or any iterable) to the end of the current list.
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.
They take exact same time.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With