ruk·si

🐍 Python
Lists

Updated at 2018-06-09 17:20

Lists are mutable sequences of data.

from typing import List

numbers: List[str] = ['one', 'two', 'three']
assert type(numbers) == list
assert numbers[1] == 'two'

del numbers[1]
assert numbers == ['one', 'three']

numbers.append('four')
assert numbers == ['one', 'three', 'four']

You merge lists with +.

from typing import List

numbers: List[int] = [1, 2] + [3, 4] + [5]
assert numbers == [1, 2, 3, 4, 5]

Prefer adding elements at the end of lists. Has better performance.

from typing import List

my_list: List[int] = []
my_list.append(1)
my_list.append(2)
my_list.append(3)
assert my_list == [1, 2, 3]
assert my_list.pop() == 3
assert my_list == [1, 2]

Never modify a list while iterating over it.

# bad
odd = lambda x: bool(x % 2)
numbers = [n for n in range(10)]
for i in range(len(numbers)):
    if odd(numbers[i]):
        del numbers[i]  # IndexError

# good
odd = lambda x: bool(x % 2)
numbers = [n for n in range(10)]
numbers[:] = [n for n in numbers if not odd(n)]

Avoid overly complex list comprehensions.

# bad
return (
    (x, y, z)
    for x in xrange(5)
    for y in xrange(5)
    if x != y
    for z in xrange(5)
    if y != z)

# good
eat(jelly_bean for jelly_bean in jelly_beans if jelly_bean.color == 'black')

Source

  • Python Tricks The Book, Dan Bader
  • Fluent Python, Luciano Ramalho