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:
On Line 2 we're creating an empty list. We can use the my_list variable to add items to the list and subsequently manage them.
Line 5 declares a list of integers.
Line 8 declares a list that contains five strings.
Line 11 is a heterogeneous list containing five different (data) type values: an integer, three strings, another integer, a float, and a boolean. This is a good example of the power of lists, since they can hold mixed data type values they are well suited for storing data like this example--an employee record.
And Line 14 demonstrates a nested lie, meaning there are lists inside of the list. For example, ["Apple", "Cherry", "Pear"] is a list at position [0] in the nested_list list. Also, notice that while there are lists inside the nested_list list, there can also be simple single (non-list) values in the list as well.
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])
Code Line 2: Demonstrates that we can create an empty list. This is often done to prepare for some type of data handling process.
Output Line 1: Shows the result of printing the empty list, Python displays the [] brackets but the list is empty.
Code Line 7: Shows the creation of a list containing 4 integers. Note the syntax, the list of values that will be stored in the list are separated by commas.
Output Line 3: This shows the result of printing the integer list.
Code Line 9: Demonstrates how we can get a single list item value by using the index of the list. In this case, we're accessing the list item at index [3].
Output Line 4: Shows the output of printing the list item at index [3].
Code Line 10: This shows that we can also use slicing syntax to access a subset of items from the list. In this example, we're accessing the items at [0:2].
Output Line 5: Shows the output of printing the subset of items at [0:2].
Code Lines 14 thru 17: Demonstrate similar list operations as shown above, this time declaring and using a string list to create a list of strings, printing the list fully, and also with index slicing.
Output Lines 7 thru 9: Show printing from the string list.
Code Line 21: Demonstrates the creation of a mixed data-type (heterogeneous) list. In this example, we're simulating an employee record that contains various pieces of information about an employee.
Output Lines 11 & 12: Demonstrate printing the mixed data type list.
Code Line 28: Declares a nested (sometimes called a multidimensional) list. In this example, the item at index [0] in the nested_list list is a list of strings. There is another nested list at index [2] of the nested_list list.
Output Lines 14 thru 18: Demonstrate the output of Code Lines 29 thru 33. Study the syntax carefully to see how to access nested list values.
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:
Code Line 1 is a for loop, but the syntax is a bit different from what we've seen previously. With lists, we can use in [listname] instead of having to define a range(). The reason this works is that lists are iterables, meaning they are sequences of values that Python can traverse one value at a time.
Note that we use a variable to be able to access each item in the list as the for loop iterates.
The for loop automatically sets the number of iterations to the number of items in the list.
Each time the loop iterates, the variable i is set to the index (from 0 to the length - 1) of the list so when the print(i) statement runs, it prints that value at that index.
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:
Code Line 1 initializes a variable that we'll use to hold the running total inside our loop.
Code Line 3 is our for loop, note it is the same syntax as the for loop in Example 1 above.
Each time the loop iterates tot is set to the previous tot plus the value in i, which is the value in the list at index position i.
When the loop ends, tot contains the total of all of the list items added together.
Code Line 5: Prints the result of our summation process.
This is a good (simple) example of a use of iterating through lists.
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:
Code Line 1: Declares and initializes our list.
Code Line 2: Declares and initializes a counter variable for our loop.
Code Line 3: We set up our while loop condition to compare i (initialized at the start to zero) to the length of the list (using the len() function).
Code Line 4: For each iteration, we print the list item based on its index, we use i as the index as it started with zero and will be incremented on Code Line 5 each iteration.
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.
Code Line 1: I create a list called num_list and assign it a list of the whole numbers, 1 thru 9 and 0.
Code Line 2: I print the list, which appears on Output Line 1.
Code Line 3: I then use an index of num_list to change that list item's value from 0 to 10.
Code Line 4: I print the list again to show the change, which appears on Output Line 2.
Code Line 5: Using slice notation, I update 3 of the list items at once. Using a slice allows us to specify a series of values to update and then on the right side of the assignment operator we list the values in [ ] brackets.
Code Line 6: I print the list again to show the change, which appears on Output Line 3.
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)
Code Line 2: Prints the original state of our list for comparison.
Code Lines 4 & 5: These two lines use the append() list method to append (add to the end of the list) a value.
Code Line 6: Prints the updated list, not the difference between Output Lines 1 & 2.
Code Line 8: Next the extend() method is used to extend the list by adding three additional values.
Output Line 3: This shows the result of using the extend() method from the print statement on Code Line 9.
Code Lines 11 & 13: Use the insert() method to insert values into the list. Insert places the new value at the position provided by the first parameter of the insert() method. The list items after that point are pushed forward so their indexes change. Study the result on Output Lines 4 & 5.
Code Line 16: Uses the + operator to add (concatenate) values to the end of the list. This is essentially the same as using the extend() method.
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:
Code Line 1 & 2: Declares a new list and then prints the list for comparison.
Code Line 4: Uses the built-in Python function del to delete one list item by referencing its index [2].
Code Line 5: Prints the modified list for comparison, the result is seen on Output Line 2.
Code Line 7: Demonstrates using del and index slicing to delete a range of values from the list.
Code Line 8: Prints the modified list for comparison, the result is seen on Output Line 3.
Code Line 12: Demonstrates using del to delete the entire list. Using del in this way deletes the list, its contents, and the variable as well.
Code Line 13: Attempts to print the list, however, because we deleted it on Line 12, the Output Line 4 thru 7 shows an error message because we cannot print a variable that no longer exists.
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)
Code Line 6: Uses the remote() method to remove a single list item by referencing the item's value.
Output Line 2: Prints the modified list for comparison.
Code Line 11: Uses the pop method, which removes an item based on its index and returns that item's value for use in your code. In this example, we capture that value in the variable val.
Code Line 23: Uses the clear() method to remove all items from the list. The list variable however is preserved, so we can continue to use it.
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)
Code Lines 1 & 2: Declare two similar, but slightly different, lists.
Code Line 4: Prints the first list for comparison.
Code Line 5: Uses the copy method to copy list 1 into a new list.
Code Lines 6 & 7: Prints both lists to show that the copy worked.
Code Line 11: Demonstrates the count method, which counts the number of times the specified value appears in the list. Notice that list 2 is used in this example to demonstrate that the value 5 appears in the list 2 times.
Code Lines 14 & 15: This shows how the reverse method reverses the order of the items in the list. Note that this is not only for display purposes, using reverse rearranges (reverses) the items in the list.
Code Line 19: Demonstrates the use of the sort method to sort the items in the list. Note that this is not only for display purposes, using sort rearranges (sorts) the items in the list.
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)
Code Line 4: Uses the len function to return the number of items in the list.
Code Line 6: Uses the max function to return the item with the maximum value.
Code Line 8: Uses the min function to return the item with the minimum value.
Code Lines 10 & 11: Use the in function to determine if the specified value is contained in the list. It returns True if the value is in the list and False if the value is not in the list.
Code Line 16: Declares a second list.
Code Line 17: Demonstrates using the equality operator == to determine if two lists are equal. Equality in this context means that the two lists have the same items and that they are in the same order.
Code Lines 18 & 19: Sorts the two lists.
Code Line 20: Again demonstrates using the equality operator == to determine if two lists are equal. This time they are equal because they have the same values and they were both sorted on Lines 18 & 19.
Code Line 24: Demonstrates using the + operator to concatenate the two lists together.
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
Python Code
print("-" * 60, "\nThis program will prompt you to enter integers greater\n"
"than zero. You can enter as many integers as you like.\n"
"When you are finished, enter Zero.")
print("-" * 60, "\n")
user_ints = []
while True:
user_int = int(input("Enter an Integer: "))
if user_int > 0:
user_ints.append(user_int)
continue
else:
break
if len(user_ints) > 0:
print("\nYour integers sorted in ascending order:")
user_ints.sort()
for i in user_ints:
print(i)
else:
print("No integers were entered.")
Solution Notes:
Code Lines 1 thru 4 : Prints the formatted user instructions.
Code Line 5: Declares an empty list in preparation for use in the loop.
Code Line 6: Starts a while loop using True (infinite) as the condition.
Code Line 7: Prompts the user for an integer.
Code Line 8: Decision statement to determine if the user entered a value greater than zero.
Code Line 9: Since the user entered a value greater than zero, append the value to our list.
Code Line 10: Since the user entered a value greater than zero, use continue to continue the loop and prompt the user again.
Code Line 11 & 12: This is the else portion of our decision, which indicates that they entered a value less than 1. In this case, we want to exit the loop, which we do with break on Code Line 12.
Code Line 13: We use a decision statement here to confirm that the user entered some integers.
Code Line 14: Prints an informative statement for the user.
Code Line 15: First we sort the list so that the integers are in ascending order.
Code Line 16: We then use a for loop to iterate through the sorted list.
Code Line 17: And print each item in the list.
Code Line 18: If the user enters 0 in the first iteration, the list will be empty so the else portion of the decision runs.
Code Line 19: We inform the user that the list is empty.
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
Python Code
print("-" * 60, "\nThis program will prompt you to enter integers greater\n"
"than zero. You can enter as many integers as you like.\n"
"When you are finished, enter Zero.")
print("-" * 60, "\n")
user_ints = []
evens = []
odds = []
while True:
user_int = int(input("Enter an Integer: "))
if user_int > 0:
if user_int % 2 == 0:
evens.append(user_int)
else:
odds.append(user_int)
continue
else:
break
if len(evens) > 0:
print("\nYou entered the following even integers:")
evens.sort()
for i in evens:
print(i)
else:
print("\nYou entered no even integers.")
if len(odds) > 0:
print("\nYou entered the following odd integers:")
odds.sort()
for i in odds:
print(i)
else:
print("\nYou entered no odd integers.")
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:
------------------------------
SALES REPORT
------------------------------
Number Sales: 123
Total Sales: $7,200.48
Average Sale: $58.54
Minimum Sale: $10.77
Maximum Sale: $99.25
------------------------------
Solution Notes:
Code Line 1: We declare a list containing the data values provided.
Code Line 14: Since we need a summary value for total sales that will be calculated as a running total in a loop, we declare it here and initialize it to zero.
Code Line 15: We set up a for loop that will iterate through the entire list, starting with index [0] to the end.
Code Line 16: Inside the loop we accumulate our total sales. Accumulation is a very common task that we perform on lists and other data structures inside of a loop.
Code Line 20: We can use the len() function to provide a count of the number of sales. Since each list item is a sale amount, the number of items in the list is the number of sales in this set of data. If we added or removed sale value from the list, then the number of sales would change.
Code Line 21: This line is where we're printing our accumulated total sales value that we calculated inside of the for loop above.
Code Line 22: Since average is calculated by dividing the total by the number of values, we can use the total sales accumulated amount and divide by the number of sales values in the list.
Code Line 23 & 24: We can use the min() and max() functions to provide the minimum sale and the maximum sale from the list.
Testing Recommendation: When testing code for a problem like this, use the existing data and the results of an initial run as a benchmark, then add values to the sales data and re-run the program. Confirm that your summary values change as expected based on the data you added. Also, test the opposite, remove sales records and re-run, confirm the summary values change as expected in that scenario as well.