Table of Contents » Chapter 2 : Data (Input) : Data Structures : Lists
Lists
Contents
Overview
So far, we have used variables to store various data types. We have learned that Python is dynamically typed and that a variable can hold 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 will 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 first data structure we will explore in Python is a list.
Lists are one of the most commonly used data structures in Python. They allow us to store multiple data elements together using one variable name. Here are the key 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 provides 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 complete list of list methods here ↗. |
| Can Be Nested | Lists can contain lists, that is, any list element can be a list. |
To review, a variable is a label for a storage location in memory where the value we have assigned to that variable resides. We have seen the diagram in Figure 1 before. It depicts a variable called age, which is assigned the value of 25. The label age points to a location in memory where 25 is stored.

Lists & Memory: When we want to create a list in Python, we start by creating a variable and using the assignment operator (=) to initialize our list with values. In Figure 2, we see that we're a variable my_list. We defined a list on the right side of the assignment operator, which in this example contains three values (strings): apple, orange, and pear. The list variable points to a memory address, which is the address of a 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 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.
The items stored 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 the end of the list [list_length - 1]. We can also access indexes using negative numbers, beginning from the end of the list and counting backward toward the beginning of the list.
Figure 3 depicts the five lists created in the code above:

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:
- 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.
Once we have created a list, we can update (change) the values of list items. Remember 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:
- 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.
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:
- Code Line 1: Declares and initializes our 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() list method ↗ is used to extend the list by adding three additional values.
- Output Line 3: This shows the result of using the extend() list method ↗ from the print statement on Code Line 9.
- Code Lines 11 & 13: Use the insert() list method ↗ to insert values into the list. Insert places the new value at the position provided by the first parameter of the insert() list 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() list method ↗.
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)
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:
- Code Line 1: Declares the list again.
- Code Line 6: Uses the remote() list 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 list 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() list 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)
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:
- 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.
In addition to list methods ↗, we can also use many Built-In Functions ↗ and Operators ↗ with lists as well. We saw one of the functions already above, del, which we used to delete a list. Here are some examples of other built-in functions and operators used with lists, including len(), max(), min(), in, =, ==, and +.
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:
- Code Line 2: Declares a list of integers.
- 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.
Problem 1
Write a Python program that creates a list containing 10 integers. Then, using individual print statements, print the first element, the third element, and the tenth element.
Problem 2
Write a Python program that creates a list containing the following words as individual list elements.
field
the
across
horse
dog
cow
walked
pasture
flew
over
to
a
bird
barn
ran
house
Then, use a single print statement to print a sentence of at least four words from the list. The first word of your output sentence should be appropriately capitalized, so use the appropriate string method to do so. Also, use the appropriate print function argument to add a period at the end of your output sentence. You can reuse any of the words as necessary. No hardcoding!
Problem 3
Write a Python program that does the following:
- Create a list containing five integers.
- Print the list.
- Print the length of the list.
- Print the minimum value in the list.
- Print the maximum value in the list.
- Reverse the list.
- Print the reversed list.
- Add five more values to the list.
- Print the list.
- Print the length of the list.
- Print the minimum value in the list.
- Print the maximum value in the list.
- Sort the list.
- Print the list.
- Delete the fourth item in the list.
- Print the list.
- Delete the seventh items in the list.
- Print the list.
Problem 4
Write a Python program that creates a heterogeneous list containing the following data elements for an employee: First Name (string), Last Name (string), Address (string), City (string), State (string), Zip Code (string), Phone Number (string), Email Address (string), Age (int), Hourly Wage (float), and a boolean indicator of whether the employee receives bonuses. You can use any data values you wish for the list elements. Then, write a single print statement that prints the list item in the format shown in the example shown below.
Bob Smith
1234 Someplace Street
Some City, UT 84999
(801)999-4444
bob@abc.com
Age: 40
Wage: 25.99/hourly
Bonuses: False