List

Posted on September 16, 2020


A list is used to group values together. It is written as a pair of square brackets containing comma-separated items. Several examples of a Python list are shown below.

# Ex 1 - create a list with square brackets
# ----------------------------------------------------------------------------

mylist = [1, 2, 3, 4, 5]

# Ex 2 - unpack list values
# ----------------------------------------------------------------------------

a, b, c, = [8, 9, 10]
print('a', a)
print('b', b)
print('c', c)

first, *rest = [1, 2, 3, 4, 5, 6, 7]
print('first', first)
print('rest', rest)

first, *mid, last = [1, 2, 3, 4, 5, 6, 7]
print('first', first)
print('mid', mid)
print('last', last)

# Ex 3 - enumerate a list to get index and value
# ----------------------------------------------------------------------------

letters = ['a', 'b', 'c', 'd', 'e']

for i, x in enumerate(letters):
    print(f'index = {i} and letter = {x}')

# Ex 4 - iterate over multiple lists
# ----------------------------------------------------------------------------

one = [1, 2, 3, 4, 5]
two = [2, 3, 4, 5, 6]
three = [3, 4, 5, 6, 7]

for i, j, k in zip(one, two, three):
    print('i', i, 'j', j, 'k', k)

# or use index to get each item from multiple lists
n = len(one)
for i in range(n):
    print('i', one[i], 'j', two[i], 'k', three[i])

Reverse a list

There are several ways to reverse a list.

# Example 1
# ----------------------------------------------------------------------------

# Reverse a list in-place. Fast and does not take up extra memory. Modifies
# original list.

list_one = [1, 2, 3, 4, 5]
list_one.reverse()

print('list_one\n', list_one)

# Example 2
# ----------------------------------------------------------------------------

# Slicing creates a reversed copy of the list. Takes up memory but doesn't
# modify the original list.

list_two = [6, 7, 8, 9, 10]
list_three = list_two[::-1]

print('list_three\n', list_three)

# Example 3
# ----------------------------------------------------------------------------

# Returns an iterator that returns elements in reverse order. Does not modify
# original list. Needs to be converted into a list object again.

list_four = [11, 12, 13, 14, 15]
list_five = list(reversed(list_four))

print('list_five\n', list_five)

Further reading


Back

Gavin Wiggins © 2020