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


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

Getting the second element

Getting the last element


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


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

Printing the numbers 1 to 700

Making a list of numbers from 1 to a thousand


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

Finding the maximum value

Finding the sum of all values


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

Getting the middle three items

Getting the last three items


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

Starting with an empty list

Inserting elements at a particular position


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

Removing an item by its value


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

Pop the first item in a list


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


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


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. List 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

Using a comprehension to generate a list of square numbers

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

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


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

Sorting a list permanently in reverse alphabetical order

Sorting a list temporarily

Reversing the order of a list


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

Printing a message for each item


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

Looping through a tuple

Overwriting a tuple


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

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.