Python Lists

python lists

A list stores a series of items which makes them good for keeping track of things, especially when the order or contents of the list might change. Lists are a mutable data structure, meaning you can alter that list as needed. Lists allow you to store sets of information in one place, whether you have just a few items or thousands of items. You can change a list, add new elements, delete elements, or replace elements as needed. Lists are one of Python’s most powerful features available to new programmers, and they tie together many important concepts in programming.

How To Define A Python List

Use square brackets [] to define a list. You can use commas to separate the items in a list. It makes sense to use pluralized variable names for holding your lists, as this makes the code easier to reason about (understand).

Making a list

foods = ['Eggs', 'Olives', 'Dairy', 'Meat', 'Chocolate']

How To Access List Elements

An individual element in a list can be accessed according to its position, also called the index. The index of the first element is 0, the index of the second element is 1, and so on. A Negative index specifies items beginning at the end of the list. To access a particular element, write the name of the list and then the index of the element in square brackets.

Getting the first element

first_food = foods[0]

Getting the second element

second_food = foods[1]

Getting the last element

newest_food = foods[-1]

Modifying A List Item

You can change individual elements in the list once it has been defined. You do this by referencing the index of the item you want to modify.

Changing a list element

foods[0] = 'Blueberry'
first_food = foods[0]

The range() function

The range() function makes it easy to work with a set of numbers in an efficient way. It starts at 0 by default, and stops one number below the number passed to it. In addition to range(), you can use the list() function to generate a large list of numbers.

Printing the numbers 0 to 500

for number in range(501):

Printing the numbers 1 to 700

for number in range(1, 701):

Making a list of numbers from 1 to a thousand

numbers = list(range(1, 1001))

Min Max and Sum

There are several simple operations you can run on a list containing numerical data using functions like min(), max(), and sum().

Finding the minimum value in a list

math_scores = [83, 79, 26, 47, 81, 2, 39, 79, 5, 98]
lowest = min(math_scores)

Finding the maximum value

math_scores = [83, 79, 26, 47, 81, 2, 39, 79, 5, 98]
highest = max(math_scores)

Finding the sum of all values

math_scores = [83, 79, 26, 47, 81, 2, 39, 79, 5, 98]
total_points_earned = sum(math_scores)

How To Slice A List

You can work with any group of elements from within a list. This subset of a list is called a slice. To slice a list begin with the index of the first item you want, then add a colon and the index after the last item you want. Leave off the first index to start at the beginning of the list, and leave off the last index to slice through the end of the list.

Getting the first three items

games = ['Pokemon Sword & Shield', 'Luigis Mansion', 'Killer Queen Black', 'Dragon Quest', 'Links Awakening']
first_three = games[:3]
['Pokemon Sword & Shield', 'Luigis Mansion', 'Killer Queen Black']

Getting the middle three items

middle_three = games[1:4]
['Luigis Mansion', 'Killer Queen Black', 'Dragon Quest']

Getting the last three items

last_three = games[-3:]
['Killer Queen Black', 'Dragon Quest', 'Links Awakening']

Adding Elements To A List

You can add elements to the end of a list, or you can insert them wherever you like in a list.

Adding an element to the end of the list

['Eggs', 'Olives', 'Dairy', 'Meat', 'Chocolate', 'Garlic']

Starting with an empty list

foods = []
['Onion', 'Broccoli', 'Tomato']

Inserting elements at a particular position

foods.insert(0, 'Pepper')
foods.insert(3, 'Lemon')
['Pepper', 'Onion', 'Broccoli', 'Lemon', 'Tomato']

Removing Elements From A List

You can remove elements by their position in a list, or by the value of the item. If you remove an item by its value, Python removes only the first item that has that value.

Deleting an element by its position

del foods[-1]
['Pepper', 'Onion', 'Broccoli', 'Lemon']

Removing an item by its value

['Pepper', 'Broccoli', 'Lemon']

Pop A List Item

If you want to use an element that you’re removing from a list, you can pop the element out of the list. If you think of the list like a stack of items, pop() takes an item off the top of the stack. The pop() function returns the last element in the list, but you can also pop elements from any position in the list by specifying the index you are interested in.

Pop the last item from a list

most_recent_food = foods.pop()

Pop the first item in a list

first_food = foods.pop(0)

The len() Function

To count the number of items in a list, you can use the handy len() function.

Find the length of a list

foods = ['Eggs', 'Olives', 'Dairy', 'Meat', 'Chocolate']
num_foods = len(foods)
print(f"We have {num_foods} foods.")
We have 5 foods.

Copy A List

To make a copy of a list, slice the list starting at the first item and ending at the last item. If you try to copy a list without using
this approach, whatever you do to the copied list will affect the original list as well.

Making a copy of a list

games = ['Pokemon Sword & Shield', 'Luigis Mansion', 'Killer Queen Black', 'Dragon Quest', 'Links Awakening']
copy_of_games = games[:]

['Pokemon Sword & Shield', 'Luigis Mansion', 'Killer Queen Black', 'Dragon Quest', 'Links Awakening']

List Comprehensions

You can use a loop to generate a list based on a range of numbers or on another list. This is a common operation, so Python offers a more efficient way to do it. Python comprehensions may look complicated at first; if so, use the for loop approach until you’re ready to start using comprehensions.

To write a comprehension, define an expression for the values you want to store in the list. Then write a for loop to generate input values needed to make the list.

Using a loop to generate a list of square numbers

squares = []
for x in range(1, 11):
    square = x ** 2

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Using a comprehension to generate a list of square numbers

squares = [x ** 2 for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Using a loop to convert a list of languages to upper case

languages = ['python', 'golang', 'javascript', 'sql', 'php']
upper_languages = []
for language in languages:


Using a comprehension to convert a list of languages to upper case

languages = ['python', 'golang', 'javascript', 'sql', 'php']
upper_languages = [language.upper() for language in languages]

How To Sort A List

Sorting of a list can be done with the sort() function which changes the order of a list permanently. The sorted() function on the other hand returns a copy of the list, while leaving the original list unchanged. You can sort the items in a list in alphabetical order, or reverse alphabetical order. You can also reverse the original order of the list. Lowercase and uppercase letters may affect the sort order.

Sorting a list permanently

foods = ['Eggs', 'Olives', 'Dairy', 'Meat', 'Chocolate']

['Chocolate', 'Dairy', 'Eggs', 'Meat', 'Olives']

Sorting a list permanently in reverse alphabetical order

['Olives', 'Meat', 'Eggs', 'Dairy', 'Chocolate']

Sorting a list temporarily

print(sorted(foods, reverse=True))
['Chocolate', 'Dairy', 'Eggs', 'Meat', 'Olives']
['Olives', 'Meat', 'Eggs', 'Dairy', 'Chocolate']

Reversing the order of a list

['Chocolate', 'Meat', 'Dairy', 'Olives', 'Eggs']

Loop Over A List

Lists can contain hundreds, thousands, or millions of items, so Python provides a way to loop through all the items in a list. When you set up a loop, Python pulls each item from the list one at a time and stores it in a temporary variable, which you provide a name for. This name should be the singular version of the list name. The indented block of code makes up the body of the loop, where you can work with each individual item. Any lines that are not indented run after the loop is completed.

Printing all items in a list

for food in foods:

Printing a message for each item

for food in foods:
    print(f"Eat, {food}!")
Eat, Eggs!
Eat, Olives!
Eat, Dairy!
Eat, Meat!
Eat, Chocolate!

Tuples – A Special Kind Of List

A tuple is similar to a list, except you can’t change the values in a tuple once it’s defined. This is known as being immutable. Tuples are good for storing information that shouldn’t be changed throughout the duration of a program. You define tuples using parentheses (). You can overwrite an entire tuple, but you can’t change the individual elements in a tuple.

Defining a tuple

measurements = (900, 500)

Looping through a tuple

for measurement in measurements:

Overwriting a tuple

measurements = (900, 500)
measurements = (1100, 700)
(900, 500)
(1100, 700)

Stepping Through Python Code

When you’re first learning about data structures like lists, it helps to step through how the code is working with the data in your program. Most IDE’s will provide a way you can “Step Through” the code as it executes, allowing you to see what the code is doing on each line execution. The code snippet below is a good one to use for testing the step into process in PyCharm or another IDE.

Build a list and print the items in the list

puppies = []
for puppy in puppies:
    print(f'Hello {puppy}!')
print('I love these puppies!')
print('\nThese were my first two puppies:')
old_puppies = puppies[:2]
for old_puppy in old_puppies:
del puppies[0]

pycharm step into code

In addition to stepping through your code using an IDE, you can also use a cool website like Python Tutor which provides a really interesting graphical output of your code as it runs.
python tutor visualization

Learning More About Python Lists

Python List Summary

Lists are useful data types because they allow you to write code that works on several values in a single variable. They are mutable, meaning that their contents can change. Tuples and strings are immutable and cannot be changed. Variables that contain a tuple or string value can be overwritten with a new tuple or string value. This is different than modifying the existing value in place like when using append() or remove() methods do on lists.