Subscribe Contact

Home  »  Chapter 5 : Data Structures
Lists

Overview

So far, we have used variables to store data elements of various data types. We've learned that Python is dynamically typed and that a variable can store one value at a time. We also learned that a variable is a label for a memory location in the computer where the value assigned to that variable is stored. Next, we are going to take the concept of a variable and expand on it so that we can use a single variable to refer to multiple data values at once. We do this through the use of data structures.

The List Data Structure

The first data structure we will learn is the list. Lists are one of the most used data structures in Python. They allow us to store multiple data together with one variable name. Here are some attributes of the list data structure:

List Attribute Description
Heterogeneous Lists are heterogeneous, that is, they can store different values of different data types at the same time.
Ordered The items in a list are in a set order and remain that way unless we use a list method to alter that order.
Mutable The items in a list are mutable (changeable), that is, they can be changed, added, and removed after they have been added to the list.
Allows Duplicates Since lists are indexed, which provide a unique identifier for any given item in the list, list item values can be duplicates of each other.
Indexed Lists are indexed from [0] to [length - 1], so the first item in the list is list_var[0], the second is list_var[1], etc.
Are Objects Lists are objects in Python, so they have methods and can be managed like any other object in the language.
Have Methods Because lists are objects, they have methods. You can find a full list of list methods here.
Can Be Nested Lists can contain lists, that is, any list element can be a list.


Lists & Memory (RAM)

If you recall from the variables discussion earlier in this eBook, a variable is a label for a storage location in memory where the value we have assigned to that variable resides. Variables & Memory: We saw this diagram before when we first looked at variables. It depicts a variable, called age, and we assigned the value of 25 to it in our Python code. In memory, the label age points to a location in memory where 25 is stored.



Lists & Memory: Now, if we diagram how lists are stored in memory as shown below, we see that we still have a single variable, in this example my_list. We added three values (strings) to the list: apple, orange, and pear. The list variable points to a memory address, which is the address of the block memory. Inside that block of memory, our list values are stored. We only need to use the variable and indexes (in this example, [0], [1], and [2]) to access any item in the list.



Creating Lists

Creating a list is similar to creating a variable and assigning a value to it, however, instead of one value, a list variable can be assigned a set of values. That set of values is enclosed inside square brackets [ ] on the right side of the assignment operator (=). Here is the general form of creating a list:

list_variable = [iterable(s)]
Here are several code examples:

# Empty list
my_list = []

# List of integers
int_list = [2, 4, 6, 8]

# List of strings
dow_list = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]

# Heterogeneous list
employee = [12345678, "Bob", "Smith", "Marketing", 25, 23.50, True]

# Nested (Multi-Dimensional) List (list of lists)
nested_list = [["Apple", "Cherry", "Pear"], 99, [True, False, True], 44.599]
Code Details:

List Indexing

The items we store in lists are accessible through list indexes, similar to the indexing we learned earlier with strings. Each item in a list has an index value denoted as an integer inside of square brackets [ ]. Like strings, indexing of lists starts at zero [0] and counts by 1 up to [list_length - 1]. We can also access indexes using negative numbers, beginning from the end of the list counting backward toward the beginning of the list

Here is a visual depiction of the five lists created in the code above:

Accessing List Items

Let's expand on the code above for creating the lists to demonstrate how to access items in those lists:

# Empty list
my_list = []
print(my_list)
print()

# List of integers
int_list = [2, 4, 6, 8]
print(int_list)
print(int_list[3])
print(int_list[0:2])
print()

# List of strings
dow_list = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
print(dow_list)
print(dow_list[-2])
print(dow_list[3:5])
print()

# Heterogeneous list
employee = [12345678, "Bob", "Smith", "Marketing", 25, 23.50, True]
print(employee)
hourly_rate = employee[5]
print(hourly_rate)
print()

# Nested (Multi-Dimensional) List (list of lists)
nested_list = [["Apple", "Cherry", "Pear"], 99, [True, False, True], 44.599]
print(nested_list)
print(nested_list[0])
print(nested_list[0][1])
print(nested_list[1])
print(nested_list[2][1])
Output:

[]

[2, 4, 6, 8]
8
[2, 4]

['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
Thursday
['Thursday', 'Friday']

[12345678, 'Bob', 'Smith', 'Marketing', 25, 23.5, True]
23.5

[['Apple', 'Cherry', 'Pear'], 99, [True, False, True], 44.599]
['Apple', 'Cherry', 'Pear']
Cherry
99
False
Code & Output Details:

Iterating Through Lists

When working with lists we often need to iterate through the list to access each item one at a time. There are several ways to do this, the first we'll look at is with a simple for loop.

Example 1: Using our dow_list from above here's how we could iterate through that list and print each item:

for i in dow_list:
print(i)
Output:

Monday
Tuesday
Wednesday
Thursday
Friday

Code & Output Details:

Example 2: Let's use the same for loop structure but this time we'll use the int_list and perform a calculation in the loop, which is a common use of looping through lists.

tot = 0
print(int_list)
for i in int_list:
tot = tot + i
print(tot)
Output:

[2, 4, 6, 8]
20

Code & Output Details:

Example 3: Using our dow_list from above here's how we could iterate through that list using a while loop:

dow_list = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
i = 0
while i < len(dow_list):
print(dow_list[i])
i += 1
Output:

Monday
Tuesday
Wednesday
Thursday
Friday

Code & Output Details:

Updating (Changing) Lists

Once we have created a list, we can update (change) the values of list items. Keep in mind that we can make those changes because lists are mutable (changeable).

To change the value of any existing item(s) in a list we use the list name and the index(es) of the items we want to change, the assignment operator (=), and then the new value(s). Notice the plurals in that sentence, we can update one item in a list or multiple items in a list using indexes and slices.

Examples:

num_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(num_list)
num_list[9] = 10
print(num_list)
num_list[4:6] = [99, 98, 97]
print(num_list)
Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 99, 98, 97, 7, 8, 9, 10]

Code & Output Details:

Adding List Items

We can also add new items to a list, which changes its size, and again is possible because lists are mutable (changeable). there are several approaches to adding items to a list: the list methods append(), extend(), and insert() and also using concatenation.

Examples:

num_list = [1, 2, 3, 4, 5]
print(num_list)
# Add 2 items using append() list method twice
num_list.append(111)
num_list.append(222)
print(num_list)
# Add several items at once using extend() method
num_list.extend([333, 444, 555])
print(num_list)
# Insert items using the insert() list menthod
num_list.insert(0, 666)
print(num_list)
num_list.insert(7, 777)
print(num_list)
# Use concatenation to add items to the list
num_list = num_list + [1000, 1001]
print(num_list)
Output:

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 111, 222]
[1, 2, 3, 4, 5, 111, 222, 333, 444, 555]
[666, 1, 2, 3, 4, 5, 111, 222, 333, 444, 555]
[666, 1, 2, 3, 4, 5, 111, 777, 222, 333, 444, 555]
[666, 1, 2, 3, 4, 5, 111, 777, 222, 333, 444, 555, 1000, 1001]

Code & Output Details:

Removing (Deleting) List Items

We can remove items from a list, which changes its size, and again is possible because lists are mutable (changeable). there are several approaches to removing items from a list: the list methods remove(), pop(), and clear() and also using del Python command (keyword).

Example 1:

str_list = ["AA", "BB", "CC", "DD", "EE", "FF"]
print(str_list)
# Delete one item from list using del
del str_list[2]
print(str_list)
# Delete two items from the list using del & slicing
del str_list[3:5]
print(str_list)
# Delete the entire list using del, which also removes
# the variable from memory so the list is no longer
# accessible in the program.
del str_list
print(str_list)
Output 1:

['AA', 'BB', 'CC', 'DD', 'EE', 'FF']
['AA', 'BB', 'DD', 'EE', 'FF']
['AA', 'BB', 'DD']
Traceback (most recent call last):
File "C:\Users\john\PycharmProjects\DemoProject\Demo.py", line 16, in 
print(str_list)
NameError: name 'str_list' is not defined

Example 1 Code & Output Details:

Example 2:

str_list = ["AA", "BB", "CC", "DD", "EE", "FF"]
print(str_list)
# Use remove() list method to remove the first
# instance of the value specified, in this case,
# the first instance of "BB" is removed
str_list.remove("BB")
print(str_list)
# Use pop() to pop the value at index 3, which
# removes it from the list and also returns
# the value stored at that index
val = str_list.pop(3)
print(str_list)
print(val)
# Use pop() with no specified value, which
# removes the last item in the list and also
# returns the value stored there
val = str_list.pop()
print(str_list)
print(val)
# Use the clear() list method to empty the
# list. The list variable remains in memory
# so we can continue to use it.
str_list.clear()
print(str_list)
Output 1:

['AA', 'BB', 'CC', 'DD', 'EE', 'FF']
['AA', 'CC', 'DD', 'EE', 'FF']
['AA', 'CC', 'DD', 'FF']
EE
['AA', 'CC', 'DD']
FF
[]

Example 2 Code & Output Details:

Additional List Methods

We've seen several list methods so far in the examples above. There are other list methods available as well. Here are some examples of other list methods and their uses:

Examples:

int_list1 = [1, 2, 3, 4, 5]
int_list2 = [1, 2, 5, 4, 5]
# Copy a list
print(int_list1)
new_int_list = int_list1.copy()
print(int_list1)
print(new_int_list)
print()
# Count how many times a specified
# value appears in a list
print(int_list2.count(5))
# Reverse the items in a list
print(int_list1)
int_list1.reverse()
print(int_list1)
print()
# Sort a list
print(int_list2)
int_list2.sort()
print(int_list2)
Output:

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

2

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

[1, 2, 5, 4, 5]
[1, 2, 4, 5, 5]

Code & Output Details:

Built-In Python Functions & Operators with Lists

In addition to list methods, we can also use many built-in Python functions with lists as well. We saw one of these already above, del which we used to delete a list. Here are some examples of other built-in functions used with lists:

Examples:

# Built-In Functions
int_list1 = [1, 2, 3, 4, 5]
# Determine the length of a list
print(len(int_list1))
# Determine the max value in a list
print(max(int_list1))
# Determine the minimum value in a list
print(min(int_list1))
# Determine if a specified value is in a list
print(2 in int_list1)
print(99 in int_list1)

# Operators
# Determine if two lists are the same
# using the equality operator
int_list2 = [1, 2, 3, 5, 4]
print(int_list1 == int_list2)
int_list1.sort()
int_list2.sort()
print(int_list1 == int_list2)
# Combine two lists together Using
# the + (addition/concatenation)
# Operator
print(int_list1 + int_list2)
Output:

5
5
1
True
False
False
True
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]

Code & Output Details:

Practice Problems

Problem 1

Write a Python program that prompts the user for a series of integers greater than zero and then when they finish entering values, print them in ascending order. Your program should provide the user with instructions and use a loop to allow the user to enter as many values as they wish. In your instructions, tell them to enter zero to indicate they are finished entering integers. As the user enters integers, inside your loop add each value to a list. When the user enters zero to finish, sort the list and then use a loop to iterate through the sorted list and print the integers in sorted order. Your output should be well-formatted for readability.

A sample run will look something like this:

------------------------------------------------------------
This program will prompt you to enter integers greater
than zero. You can enter as many integers as you like.
When you are finished, enter Zero.
------------------------------------------------------------

Enter an Integer: 21
Enter an Integer: 10
Enter an Integer: 50
Enter an Integer: 33
Enter an Integer: 5
Enter an Integer: 0

Your integers sorted in ascending order:
5
10
21
33
50



Problem 2

Write a Python program that prompts the user for a series of integers greater than zero and then when they finish entering values, print them separated into two groups: odd numbers and even numbers. Your program should provide the user with instructions and use a loop to allow the user to enter as many values as they wish. In your instructions, tell them to enter zero to indicate they are finished entering integers. As the user enters integers, inside your loop, determine if the entered value is odd or even. If it is odd add it to a list of odd numbers and if it is even add it to a list of even numbers. When the user enters zero to finish, sort the two lists and then use loops to iterate through the sorted lists and print the odd integers and then the even integers in sorted order. Your output should be well-formatted for readability. Hint 1: Remember we can use the modulus operator (%) to determine if a value is even or odd. Hint 2: You may need to nest decision statements (if inside of an if) for this problem.

A sample run will look something like this:

------------------------------------------------------------
This program will prompt you to enter integers greater
than zero. You can enter as many integers as you like.
When you are finished, enter Zero.
------------------------------------------------------------

Enter an Integer: 1
Enter an Integer: 2
Enter an Integer: 3
Enter an Integer: 4
Enter an Integer: 5
Enter an Integer: 6
Enter an Integer: 7
Enter an Integer: 8
Enter an Integer: 9
Enter an Integer: 0

You entered the following even integers:
2
4
6
8

You entered the following odd integers:
1
3
5
7
9



Problem 3

Write a Python program that creates a list from a set of numbers that represent sales (provided below) and produces a sales report based on those numbers. The sales report should be well-formatted and provide the following details:

  • Number of sales
  • Total of all sales combined
  • Average sale
  • Minimum sale
  • Maximum sale
Here is the sales data to use in the program:


93.89, 55.63, 23.82, 70.72, 19.82, 24.44, 30.41, 55.27, 81.34, 60.95, 64.64, 73.95, 68.47, 98.96, 18.28, 35.37, 94.19, 26.84, 68.34, 95.81, 31.29, 60.43, 19.77, 19.37, 66.18, 69.63, 30.41, 24.36, 79.19, 90.36, 98.22, 45.45, 48.43, 89.37, 22.25, 80.13, 52.73, 66.66, 73.38, 42.56, 47.31, 93.85, 41.46, 65.29, 61.74, 95.76, 64.51, 89.88, 88.37, 52.81, 59.70, 41.87, 47.67, 43.51, 89.22, 95.58, 65.45, 30.76, 93.50, 26.44, 36.68, 63.95, 51.63, 35.39, 40.12, 43.69, 10.77, 52.45, 28.75, 46.87, 58.35, 12.39, 78.37, 27.91, 51.74, 89.23, 59.12, 91.84, 56.18, 12.73, 26.32, 49.22, 29.37, 19.34, 26.72, 75.80, 99.25, 18.93, 66.28, 84.38, 80.73, 49.65, 93.79, 46.39, 87.26, 47.15, 72.84, 90.50, 84.86, 36.78, 81.40, 33.10, 47.51, 87.10, 78.49, 76.37, 42.56, 95.55, 73.12, 83.29, 71.89, 49.52, 59.45, 46.19, 96.97, 85.78, 64.74, 32.34, 69.54, 29.77, 78.36, 71.33, 46.40




 


«  Previous : Data Structures : Concepts
Next : Data Structures : Dictionaries  »



© 2023 John Gordon
Cascade Street Publishing, LLC