Skip to main content

Intro on Lists

Note☆ Learning Objectives
  • Create lists with multiple values.
  • Create an empty list.
  • Use the built-in functions len(), sum(), min(), max() to find the length, total value and extrema of a list.
  • Use the append() method to add an element at the end of an existing list.
Warning☆ Additional Objectives
  • Use the insert() method to add an element at a specific position.
  • Use the pop() method to remove an element at a given position.

Why use lists?

When you need to read, store, process, and print large amounts of numbers, creating a separate variable for each one is impractical. For instance, reading five numbers individually would be cumbersome and time-consuming.

var1 = 10
var2 = 5
var3 = 7
var4 = 2
var5 = 1

Creating a list

A list is a table of values, allowing a program to store multiple values inside a single variable.

NoteBASIC SYNTAX
list_name = [value1, value2, value3]
  • Create a list using [ ]
  • List out the values seperated by commas ,
  • The various values may be of different data types (altough not recommended)
  • Assign it to a variable.
  • This creates a list with list_name containing all the listed values.

Example

numbers = [10, 5, 7, 2, 1]

This creates a list named numbers containing five values. List is a special variable, which can hold more than one value at a time. Using lists makes it convenient to manage and process large sets of data, such as sorting numbers in ascending order. This approach simplifies code and improves readability.

Heterogenous lists

The elements inside a list may have different types. Some of them may be integers, others floats, and yet others may be lists.

Example

magic_bag = [True, 1, 5, "orange", 55.89]

print(f"Here's a bag of stuff: {magic_bag}")
Here's a bag of stuff: [True, 1, 5, 'orange', 55.89]
ImportantAvoid heterogenous lists

Altough possible, using a heterogenouse list (mixing elements of different data types) is not recommended. As you’ll discover later, lists can be used to calculate statistics or rearranged in specific order. These functionalities will fail if the values aren’t of the same type!

Empty List

You may also create a list without any values. This can be useful if the values are added later during the program execution. You can add element using append() as described later in this lesson.

my_list = []

The length of list

The length of a list, i.e the number of elements it contains, can change during program execution as new elements are added or existing elements are removed. This makes lists very dynamic.

To check the current length of a list, you can use the len() function, which takes the list’s name as an argument and returns the number of elements currently in the list.

Example:

The sum of elements

The sum of all elements in a list might be very useful for computing averages or accumulated totals.

To get the sum simply call the function sum() and pass the list as argument.

Example

Example

To calculate the average value, you can use both sum() and len() as such:

The extrema (min/max)

The smallest and largest value in a list can be obtained with min() and max() which are also built-in python functions.

Example: Min/Max

Adding elements to a list: append()

append()

A new element may be added to the end of the existing list:

NoteBASIC SYNTAX
my_list.append(value)
  • Such an operation is performed by a method named append(). It takes its argument’s value and puts it at the end of the list which owns the method.

  • The list’s length then increases by one.

Example

numbers = [1,2,3]
numbers.append(4) # Will add 4 at the end of the list

print(numbers)
[1, 2, 3, 4]

Example with loops

The .append() method can also be called within a loop:

numbers = [1,2,3]
for i in range(10):
  numbers.append(4) # Will add 4 at the end of the list 10 times

print(numbers)
[1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]

List methods

insert()

The insert() method is also for adding elements but is a bit smarter ‒ it can add a new element at any place in the list, not only at the end.

NoteBASIC SYNTAX
my_list.insert(location, value)

To insert an element into a list, the insert() method takes two arguments:

  • The position where the new element should be inserted. All existing elements starting with this position onward are shifted to the right to make room.
  • The new element to be inserted.

Example:

The append() method in Python adds an element to the end of a list, while the insert() method inserts an element at a specified position, shifting subsequent elements to the right. The len() function returns the number of elements in the list.

Pay attention to what happens after using insert(): the former first element is now the second, the second the third, and so on.

pop()

An element may be removed from the list at a specific position using the pop() method:

NoteBASIC SYNTAX
my_list.pop(index)

removed_item = my_list.pop()
print(f"We have removed {removed_item} from the list.")
  • The pop() method removes the element at the specified position (given by index) and returns its value.
  • If no index is provided, pop() removes and returns the last element in the list.

How It Works:

  1. The list’s length decreases by one after the operation.
  2. Attempting to pop() an index that doesn’t exist raises an IndexError.

Example:

Summary

Operation Example Result
Create an empty list a = [] a is []
Create a list a = [1,2,3,3] a is [1,2,3,3]
Access item a[0] 1
Change item a[1] = 10 a is [1,10,3,3]
Add item a.append(5) a is [1,10,3,3,5]
Add Item a.insert(2,88) a is [1,10,88,3,3,5]
Remove first occurrence a.remove(3) a is [1,10,88,3,5]
Remove last item a.pop() a is [1,10,88,3], returns 5
Remove item by index a.pop(0) a is [10,88,3], returns 1
Count items len(a) 3