3️⃣ 📘 Python Lists

A Python list is an ordered collection of objects that can be of different types, including other lists. Lists are created using square brackets and can be modified, searched, and iterated over. They are an essential part of the Python language and are used in a variety of applications. Lists are also mutable, which means that the elements within a list can be changed after the list has been created.

💡 Convert Tuple to List

Use the function list() to convert a tuple or set to a list. Once it is a list type, it gets the extra functions available for a list such as sort(), append(), remove(), and pop().

y = (1,2.7,3.8e3,4.9)
y = list(y)
type(y)
    list

The range(end) function can generate a list such as [0,1,2] or with range(start,end,increment) to generate [3,5,7,9].

print(list(range(3)))
print(list(range(3,10,2)))
    [0, 1, 2]
    [3, 5, 7, 9]

💡 Create New List

Create a list of numbers. Mixed element types with integers, floats, and strings are also possible.

y = [1,2.7,3.8e3,4.9]

📝 Print List

Print the list with the print() function.

print(y)
type(y)
    [1, 2.7, 3800.0, 4.9]

    list

📑 Unpack List

Each element of a list is accessed when used as an iterator in a for loop.

for yi in y:
    print(yi)
    1
    2.7
    3800.0
    4.9

Use enumerate() to return the index i and the value yi of each item in the list.

for i,yi in enumerate(y):
    print(i,yi)
    0 1
    1 2.7
    2 3800.0
    3 4.9

📃 List Elements

Similar to a tuple, the list is referenced by an index with square brackets. The first element is y[0] because a Python tuple or list starts with index-0.

    1

The last element of the list is y[-1].

    4.9

🔍 Find Item in List

Determine if an item is in a list with the in operator or count the number of occurances with y.count(2.7).

2.7 in y
    True

🔪 List Slice

A list slice is a subset of the full list with y[start:end:increment]. It is defined as a range of values such as y[1:3].

z = y[1:3]
print(y)
print(z)
    [1, 2.7, 3800.0, 4.9]
    [2.7, 3800.0]

Changing the slice does not change the original list.

z[0] = 3.7
print('Slice: ', z)
print('Original ', y)
    Slice:  [3.7, 3800.0]
    Original  [1, 2.7, 3800.0, 4.9]

Leave out the number in y[start:end:increment] to start at the beginning or terminate at the end. Every other item (increment 2) in a list is y[::2].

y[::2]
    [1, 3800.0]

🧦 Copy List

When copying a list, use the copy() function to create the new list or the two lists (z and y) reference the same values in memory.

print('Before: ',y)
z = y # use y.copy() instead
z[0] += 1
print('After: ',y)
    Before:  [1, 2.7, 3800.0, 4.9]
    After:  [2, 2.7, 3800.0, 4.9]

➕ Add to List

Items can be added to the end of a list using the append() function. The item can be any object such as a number or string.

print('Before: ',y)
y.append('item')
print('After: ',y)
    Before:  [2, 2.7, 3800.0, 4.9]
    After:  [2, 2.7, 3800.0, 4.9, 'item']

The item can also be another list such as [3,2,1] added to the end.

print('Before: ',y)
y.append([3,2,1])
print('After: ',y)
    Before:  [2, 2.7, 3800.0, 4.9, 'item']
    After:  [2, 2.7, 3800.0, 4.9, 'item', [3, 2, 1]]

🗑 Remove from List

List elements can also be removed. Use the remove() function to eliminate the first instance of the object from the list.

print('Before: ',y)
y.remove('item')
print('After: ',y)
    Before:  [2, 2.7, 3800.0, 4.9, 'item', [3, 2, 1]]
    After:  [2, 2.7, 3800.0, 4.9, [3, 2, 1]]

✂ Remove Element by Index

The remove() function finds the first instance of the object from the list. Items can also be removed by index reference with the pop() function. Remove the last element of the list with pop(-1).

print('Before: ',y)
y.pop(-1)
print('After: ',y)
    Before:  [2, 2.7, 3800.0, 4.9, [3, 2, 1]]
    After:  [2, 2.7, 3800.0, 4.9]

Another way to remove an item from a list is with the del built-in function.

print('Before: ',y)
del y[-1]
print('After: ',y)
    Before:  [2, 2.7, 3800.0, 4.9]
    After:  [2, 2.7, 3800.0]

⚙ Insert Element at Index

The append() function adds to the end of the list. The insert() function adds an element to a specified index location such as y.insert(1,4.4) that adds 4.4 the the index-1 location.

print('Before: ',y)
y.insert(1,4.4)
print('After: ',y)
    Before:  [2, 2.7, 3800.0]
    After:  [2, 4.4, 2.7, 3800.0]

🔧 Extend List

The extend() function adds a new list or tuple to the end of an existing list. The append() function does not work to extend the list because the new element would be added as a single object.

print('Before: ',y)
y.extend([1,2,3])
print('After: ',y)
    Before:  [2, 4.4, 2.7, 3800.0]
    After:  [2, 4.4, 2.7, 3800.0, 1, 2, 3]

🔨 List Comprehension

A list comprehension builds a list from an existing list.

    newlist = [expression for item in iterable]

An example is to add one to each element of the list with [i+1 for i in y].

print('Before: ',y)
y = [i+1 for i in y]
print('After: ',y)
    Before:  [2, 4.4, 2.7, 3800.0, 1, 2, 3]
    After:  [3, 5.4, 3.7, 3801.0, 2, 3, 4]

A list comprehension can also have a conditional statement at the end to shorten the list to those items that meet the condition.

    newlist = expression for item in iterable if condition]

An example is to include only the values that are less than or equal to 3 with [i for i in y if i<=3].

print('Before: ',y)
y = [i for i in y if i<=3]
print('After: ',y)
    Before:  [3, 5.4, 3.7, 3801.0, 2, 3, 4]
    After:  [3, 2, 3]

List of Lists

A list can contain elements that are also lists. Each element in the list M is the a row in the matrix.

$$ M = \begin{bmatrix} 0 & 1 & 2 & 3\\ 10 & 11 & 12 & 13\\ 20 & 21 & 22 & 23 \end{bmatrix} $$

The matrix has 3 rows and 4 columns. Numpy arrays are introduced later as an easier way to work with matrices.

M = [[0,1,2,3],[10,11,12,13],[20,21,22,23]]
print(M[1])                  # print row 1
print([row[1] for row in M]) # print column 1 using list comprehension
print(M[1][2])               # print row 1, column 2
    [10, 11, 12, 13]
    [1, 11, 21]
    12

🔑 List Attributes and Methods with dir

Use the dir() function to list all attributes (constants, properties) and methods (functions) that are available with an object.

dir(y)

A list has the following functions:

  • append - add to the end of a list
  • clear - delete all elements of a list
  • copy - create a copy of the list
  • count - count the number of matching elements
  • extend - append elements of an iterable (e.g. list)
  • index - find first index of the matching element
  • insert - add object at specified index
  • pop - remove item at specified index
  • remove - remove by object reference
  • reverse - sort in reverse (descending) order
  • sort - sort list in ascending order

💻 Exercise 3A

Complete the following steps with list operations.

  1. Start with an empty list: [] called z.
  2. Append the value 2.
  3. Insert value 3.75 at index 1.
  4. Extend the numbers to the end of z: [4,5,1].
  5. Insert value 3 at index 0.
  6. Sort the list in ascending order.
  7. Remove (pop) index 3.
  8. Print the result.

Check the result. It should be [1,2,3,4,5] if all steps are completed successfully.

z=[]
z.append(2)
z.insert(1,3.75)
z.extend([4,5,1])
z.insert(0,3)
z.sort()
z.pop(3)
print(z)

💻 Exercise 3B

Simulate rolling two 6-sided dice 🎲🎲 10,000 times.

import random
for i in range(10000):
    v = random.randint(1,6) + random.randint(1,6)

Append the value v in a list after each roll. Display the count and percentage each value was rolled between 2 and 12. How closely do the random rolls agree with the probability of 1/36 = 2.77% for 2 and 12?

import random
d = []
for i in range(10000):
    v = random.randint(1,6) + random.randint(1,6)
    d.append(v)
for i in range(2,13):
    print(f'Value: {i}',f'Count: {d.count(i)}',\
          f'Percent: {100*d.count(i)/len(d)}%')

✅ Knowledge Check

1. What is the result of the following operation?

y = [1,2.7,3.8e3,4.9]
z = y
z[0] = 5

What is the value of y[0] after executing the above code?

A. 1
Incorrect. Assigning z = y makes both variables point to the same list in memory. Any changes made to z will reflect in y.
B. 5
Correct. Assigning z = y makes both variables point to the same list in memory. Modifying z will also modify y.
C. 2.7
Incorrect. 2.7 is the second element in the list, not the first.
D. None of the above
Incorrect. The correct answer is option B.

2. Given the following list comprehension:

y = [2, 4, 6, 8]
new_list = [i+1 for i in y if i <= 6]

What will be the value of new_list?

A. [3, 5, 7, 9]
Incorrect. The condition in the list comprehension only includes numbers from y that are less than or equal to 6.
B. [3, 5, 7]
Correct. Only the numbers 2, 4, and 6 from y meet the condition. When incremented by 1, they become 3, 5, and 7 respectively.
C. [2, 4, 6]
Incorrect. The list comprehension increments each number by 1.
D. [3, 5]
Incorrect. The number 6 from y also meets the condition and should be included.
💬