Skip to content

Instantly share code, notes, and snippets.

@andersy005
Last active March 7, 2018 04:38
Show Gist options
  • Save andersy005/b06072d933e7c55d1f73cc6b7641b165 to your computer and use it in GitHub Desktop.
Save andersy005/b06072d933e7c55d1f73cc6b7641b165 to your computer and use it in GitHub Desktop.
Python List tricks

Extending and Appending Lists with the '+'-Operator

import time

n = 100000

start_time = time.time()
l = []
for i in range(n):
    l = l + [i * 2]
print('l = l + [...]: ', time.time() - start_time)

start_time = time.time()
l = []
for i in range(n):
    l += [i * 2]
print('l += [...]: ', time.time() - start_time)

start_time = time.time()
l = []
for i in range(n):
    l.append(i * 2)
print('l.append(...): ', time.time() - start_time)

l = l + [...]: 42.01468086242676

l += [...]: 0.021297931671142578

l.append(...): 0.01938176155090332

We can see that the "+" operator is about 2167 slower than the append method. The explanation is easy:

If we use the append method, we will simply append a further element to the list in each loop pass. Now we come to the first loop, in which we use l = l + [i * 2]. The list will be copied in every loop pass. The new element will be added to the copy of the list and result will be reassigned to the variable l. After this the old list will have to be removed by Python, because it is not referenced anymore. We can also see that the version with the augmented assignment ("+="), the loop in the middle, is only slightly slower than the version using "append".

Removing an element with remove

Remove the first occurrence of x from the list s. If x is not contained in the list, a ValueError will be raised.

>>> colours = ["red", "green", "blue", "green", "yellow"]
>>> colours.remove("green")
>>> colours
['red', 'blue', 'green', 'yellow']
>>> colours.remove("green")
>>> colours
['red', 'blue', 'yellow']
>>> colours.remove("green")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
>>> 

Find the position of an Element in a List

list.index(value, [start, [stop]]) -> integer -- return first index of value. Raises ValueError if the value is not present.

>>> colours = ["red", "green", "blue", "green", "yellow"]
>>> colours.index("green")
1
>>> colours.index("green", 2)
3
>>> colours.index("green", 3,4)
3
>>> colours.index("black")
Traceback (most recent call last):
  File "", line 1, in 
ValueError: 'black' is not in list
>>> 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment