Lists

Snippets for working with lists. A list stores a series of items in a particular order.

Accessing and slicing a list

# get the first element
lst[0]

# get the last element
lst[-1]

# get the Nth element
lst[7]

# get first 3 elements
lst[:3]

# get last 3 elements
lst[-3:]

# get elements from Mth (inclusive) to Nth (exclusive)
lst[M:N]

# get the index position of the first occurrence of an element
first_indx_pos = lst.index('element')

Looping over lists

# walk a list
for item in lst:
    statement

# walk a list with counter/index (counter starts at 0)
for counter, item in enumerate(lst):
    statement

# walk a list with counter/index (counter starts at 3)
for counter, item in enumerate(lst, start=3):
    statement

# walk over two same size lists
for item_lst1, item_lst2 in zip(lst1, lst2):
    statement

Adding elements

# append one element at end of list
lst = ['a', 'b', 'c']
lst.append('7')
print(lst)

# Output
['a', 'b', 'c', '7']

# insert one element at specific index position
lst = ['a', 'b', 'c']
lst.insert(1, '8')
print(lst)

# Output
['a', '8', 'b', 'c']

# append elements of other iterable
lst = ['a', 'b', 'c']
other_lst = ['1', '2', '3']
lst.extend(other_lst)
print(lst)

# Output
['a', 'b', 'c', '1', '2', '3']

# append elements of other iterable with `+` operator
lst = ['a', 'b', 'c']
other_lst = ['1', '2', '3']
lst = lst + other_lst
print(lst)

# Output
['a', 'b', 'c', '1', '2', '3']

Removing elements

# remove element by value (only first element removed!)
lst = ['a', 'b', 'a', 'c']
lst.remove('a')
print(lst)

# Output
['b', 'a', 'c']

# remove element by index position
lst = ['a', 'b', 'a', 'c']
del lst[2]
print(lst)

# Output
['a', 'b', 'c']

# remove all items from the list
lst = ['a', 'b', 'a', 'c']
lst.clear()
print(lst)

# Output
[]

# remove all items from the list with `del`
lst = ['a', 'b', 'a', 'c']
del lst[:]
print(lst)

# Output
[]

Sorting and reversing lists

# permanent sort (in place)
lst = ['d', 'b', 'a', 'e']
lst.sort()
print(lst)

# Output
['a', 'b', 'd', 'e']

# permanent sort (in place) in reverse order
lst = ['d', 'b', 'a', 'e']
lst.sort(reverse=True)
print(lst)

# Output
['e', 'd', 'b', 'a']

# temporary sort (returns a new sorted list)
lst = ['d', 'b', 'a', 'e']
new_lst = sorted(lst, reverse=False)
print('original list unchanged:', lst)
print('new list sorted:', new_lst)

# Output
original list unchanged: ['d', 'b', 'a', 'e']
new list sorted: ['a', 'b', 'd', 'e']

# reverse the order of the list
lst = [1, 4, 2, 7]
lst.reverse()
print(lst)

# Output
[7, 2, 4, 1]

Simple statistics on numerical list

# find maximum value in a list
lst = [1, 6, 99, 3]
max_value = max(lst)
>>> max_value
99

# find minimum value in a list
lst = [1, 6, 99, 3]
min_value = min(lst)
>>> min_value

# compute sum of elements of the list
lst = [1, 6, 99, 3]
sum_values = sum(lst)
>>> sum_values
109

# count number of times a specific value appears in the list
lst = [3, 1, 3, 6, 99, 3, 3]
cnt = lst.count(3)
>>> cnt
4

Shuffle a list

import random
lst = ['a', 'b', 'c', 'd']
random.shuffle(lst)
print(lst)

# Output
['d', 'b', 'a', 'c']

Randomly select an item from the list

import random
lst = ['a', 'b', 'c', 'd']
sel = random.choice(lst)
print(sel)

# Output
'c'

Combine lists with zip iterator

numbers = [1, 2, 3]
letters = ['a', 'b', 'c']
# Holds an iterator object
zipped = zip(numbers, letters)

>>> type(zipped)
<class zip>

# list of tuples
>>> list(zipped)
[(1, 'a'), (2, 'b'), (3, 'c')]

Unpacking list of lists with zip and * operator

pairs = [[1, 'a'], [2, 'b'], [3, 'c'], [4, 'd'], [5, 'e']]
# returns objects of class `tuple`
numbers, letters = zip(*pairs)
print(numbers)
print(letters)

# Output
(1, 2, 3, 4, 5)
('a', 'b', 'c', 'd', 'e')

List comprehension

[expression for item in list]

# same with

for item in list:
    expression

List comprehension with condition

[expression for item in list if conditional]

# same with

for item in list:
    if conditional:
        expression

List comprehension (nested loops)

[x + y for x in lst_outer for y in lst_inner]

# same with
for x in lst_outer:
    for y in lst_inner:
       x + y

List comprehension with if..else

new_lst = ["even" if i % 2 == 0 else "odd" for i in range(5)]
print(new_lst)

# Output
['even', 'odd', 'even', 'odd', 'even']

Transpose a matrix with list comprehension

# 4 rows x 2 columns
matrix = [[1, 2], [3, 4], [5, 6], [7, 8]]
transpose = [[row[i] for row in matrix] for i in range(2)]
# transposed matrix will have 2 rows x 4 columns
print (transpose)

# Output
[[1, 3, 5, 7], [2, 4, 6, 8]]