Skip to content

List

An ordered collection of elements

Details Tips:

  • Lists can be efficiently used as a stack through append() (for push) and pop().
  • Sorting seems to be broken for numeric lists containing NaN

Create list

Action Code Details
Empty list
[]
List with single element
['hello']
Define with values
[1, 3, 9]
Define with n repeated values v
[v] * n
List of n increasing counts, starting from zero
list(range(n))
List of increasing counts, starting from zero with step size s
list(range(0, n, s))
List of n decreasing counts to zero
list(range(n, 0, -1))
List of n decreasing counts to zero, with step size s
list(range(n, 0, -s))
List of increasing integers between [a, b]
list(range(a, b))
From tuple
t = (1, 3, 9)
x = list(t)
From iterable
x = list(iter)
Fully consumes the iterable.
Lists from zipped list
a = (1, 2); b = (-1, -2)
ab = zip(a, b)
a2, b2 = zip(*ab)
Sample n random integers between [ a, b ) with replacement
import random
random.choices(range(a, b), k=n)
Considerably faster than list comprehension
Sample n random integers between [ a, b ) w/o replacement
random.sample(range(a, b), n)
From lists generated dynamically by iterating over a generating function fun
list(itertools.chain.from_iterable(
    [fun(e) for e in entries]
))
Generate list of r-length permutation tuples from indices up to b
list(itertools.combinations_with_replacement(range(b), r))
Returns [(0, 0), (0, 1), ..., (b - 1, b - 1)]

Test

Action Code Details
Is list or subclass
isinstance(x, list)
Is list and not subclass
type(x) is list
Empty
not x
Not empty
x
Pairwise equal to another list
x == y
Contains None
None in x
Contains element e
e in x
Contains elements
{1, 2}.issubset(x)
Contains elements elems
set(elems).issubset(x)
Does not contain element e
e not in x
Elements are all of type t
all(isinstance(e, t) for e in x)
e.g., type str
All elements True
all(x)
Any element True
any(x)
Are elements sorted
x == sorted(x)
No duplicate elements
len(x) == len(set(x))
Has duplicate elements
len(x) != len(set(x))

extract

Action Code Details
Number of elements (length)
len(x)
Hash
hash(tuple(x))
First element
x[0]
Last element
x[-1]
Random element
import random
random.choice(x)
Number of occurrences of element
x.count(e)
Index of element
x.index(e)
Throws error if not found
Index of element in slice [a,b]
x.index(e, a, b)
Throws error if not found

Aggregate

Action Code Details
Min
min(x)
Max
max(x)
Sum
sum(x)
Mean
sum(x) / len(x)
Faster than fmean and mean from statistics
Most frequent element (mode)
statistics.mode(x)

Update

Transform

Action Code Details
Update element at index i
x[i] = e2
Update slice with list
x[2:3] = [5, 6]

Order

Action Code Details
Reverse elements
x.reverse()
Sort elements ascending
x.sort()
Sort elements descending
x.sort(reverse=True)
Sort on transformed elements, ascending
x.sort(key=str.lower)

Grow

Action Code Details
Append element
x.append(e)
Append a list
x += y
Append a list
x.extend(y)
Insert at index i
x.insert(i, e)

Shrink

Action Code Details
Clear
x.clear()
Clear
x[:] = []
Probably slower
Remove at index i
del x[i]
Remove at index i
x[i] = []
Remove slice
del x[2:3]
Remove slice
x[2:3] = []
Remove element (first occurrence)
x.remove(e)
Remove all elements with value
?
Remove last index and return the element (pop)
x.pop()
Remove at index i and return the element
x.pop(e, i)

Derive

Action Code Details
Shallow copy
x.copy()
Fastest for large lists
Shallow copy
[*x]
Fastest for small lists
Shallow copy
x[:]
Probably very slow
Shallow copy
copy.copy(x)
Not sure what the difference to .copy() is
Deep copy (don't preserve refs)
copy.deepcopy(x)
Constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

Transform

Action Code Details
Transform via expression
[e + 1 for e in x]
Map function
[fun(e) for e in x]
Map function
list(map(fun, x))
Slow
Elements to string
[str(e) for e in x]
Conditional update
[e if e != 0 else -1 for e in x]
Ternary map
[e if e > 2 else 10 for e in x]
Nested ternary map
[e if e > 2 else 10 if e < 3 else 5 for e in x]
Good luck reading this
Rank ascendingly
list(scipy.stats.rankdata(x))
Uses scipy package
Sort-index ascendingly
list(np.argsort(x))
Uses numpy package
Sort-index ascendingly
sorted(range(len(x)), key=x.__getitem__)
Sort-index ascendingly
[e[0] for e in sorted(enumerate(x), key=lambda x: x[1])]
Tedious

Order

Action Code Details
Reverse
reversed(x)
Sort ascendingly
sorted(x)
Elements must be sortable!
Sort descendingly
sorted(x, reverse=True)
Elements must be sortable!
Sort by reference order list
[x for _, x in sorted(zip(ref_order, x))]
Naturally sort string elements
from natsort import natsorted
natsorted(x)
E.g., sort as ['abc1', 'abc2', 'abc10']
Shuffle elements
random.shuffle(x)

Grow

Action Code Details
Replicate list n times
x * n
Replicate to ensure length n
from itertools import islice, cycle
list(islice(cycle(x), n))
Append element
x + [e]
Append elements
x + [e1, e2, e3]
Append a list
x + y

Shrink

Action Code Details
Slice
x[1:3]
First n elements (head)
x[:n]
Last n elements (tail)
x[-n:]
Select n elements at random
import random
random.choices(x, k=n)
Remove first n elements
x[n:]
Remove last n elements
x[:-n]
List of elements from a list of indices
[x[i] for i in indices]
Filter on condition
[e for e in x if e > 0]
Filter on predicate function
filter(fun, x)

Combine lists

Action Code Details
Concatenate lists
x + y + z

Iterate

Iterate over the elements of the list

Action Code Details
Loop over elements
for e in x:
Loop over elements and index
for i, e in enumerate(x):
Loop over elements and index, starting from index s
for i, e in enumerate(x, s):
Loop over multiple lists
for a, b in zip(x, y):
Loop over multiple lists, with index
for i, (a, b) in enumerate(zip(x, y)):
Iterate over a list of lists for each nested element
itertools.chain.from_iterable(x)

Convert

Action Code Details
Multiple assignment
x = [1, 2]
a, b = x
Tuple
tuple(x)
Set
set(x)
To dict (from keys and values)
dict(zip(keys, values))
Flatten a list of lists
list(itertools.chain.from_iterable(x))