top of page

Introduction to Python Lists

Updated: Feb 17, 2023

Arguably one of the most versatile data structures in Python are lists. At their core, they allow you to group multiple items of any data type, be it strings, integers, other lists, or objects, under one variable name. Unlike other data structures, such as tuples, lists are mutable, meaning you can add, remove, or change existing items after they're created. This article will explore the basics of Python lists and demonstrate how to use them effectively in your programming projects.



Creating lists

There are a few ways you can create a list in Python. The easiest, by far, has to be the square bracket notation. In Python, square brackets `[ ]` indicate a list, and commas separate each item. Here's an example of a list that contains the integers 1-5:

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

A list in Python can store any data type you'd like, including a collection of mixed types, such as integers and strings. Below I provide a few more examples of lists:

my_list1 = ["Python", "Java", "Rust", "C++"]
my_list2 = ["1", 2, "3", 4, "5"]


Accessing Elements

A list wouldn't be much use if we couldn't access the individual items contained within the list. To extract a specific item from a list, we'll use a concept called indexing. Indexing is a way to reference an element within a collection, a list in this case, by some positional value with the bounds [0, length-1]. Notice that the range of possible values starts at zero. This is important because the first item's index value in any collection is always zero and never one.


Looking at the `my_list` variable, the bounds of possible index values are from [0, 4], with the integer 1 having an index value of 0 and 5 an index value of 4. The end value of 4 came from counting the total number of items in the list and subtracting one from the result. To extract a specific item, we surround an index value with the bracket symbol "[index]" and place it to the right of the variable name.


Here's an example of this:

my_list = [1, 2, 3, 4, 5]
item = my_list[0]  # Index of 0
print(item)

# Output: 1

If the last element is desired, we can do the following:

my_list = [1, 2, 3, 4, 5]
item = my_list[4]  # Index of 4
print(item)

# Output: 5

While most index values will be specified as positive integers, it is possible to specify negative integer values. In the case of negative values, the bounds on possible values then become [-length, -1] where `-length` corresponds to an index value of 0 and -1 to an index value of 4 if we continue using the `my_list` variable as a reference.


While negative integer values might not seem very beneficial at first glance, they can be a lifesaver when you need the second to last element in a collection and don't know or want to calculate the length. It can also make your code much more readable because you no longer need to subtract values from the length to get at the elements you want.


Here are the two examples from above; only this time, we'll use negative index values to get the desired integers.

my_list = [1, 2, 3, 4, 5]
item = my_list[-5]  # Index of -5
print(item)

# Output: 1
my_list = [1, 2, 3, 4, 5]
item = my_list[-1]  # Index of -1
print(item)

# Output: 5


Slicing Lists

Slicing builds on the indexing principle discussed above; rather than obtaining one element from the collection (one item from the list), we can extract many or all parts from the collection. The basic syntax for slicing is as follows:

list[start : end]

Where `list` is the original list, `start` is the starting index (inclusive), and `end` is the stopping index (exclusive). Looking at the `my_list` variable again, we can extract the values 2, 3, and 4 with the following slice:

item = my_list[1:4]

To test that the slice does extract the values 2, 3, and 4, run the following code:

my_list = [1, 2, 3, 4, 5]
item = my_list[1:4]
print(item)

# Output: [2, 3, 4]

You can also omit the start or end index; sometimes, you can leave out both altogether. Here's an example of leaving out the end index to extract the integers 4 and 5 from the `my_list` variable:

my_list = [1, 2, 3, 4, 5]
item = my_list[3:]  # Omit the end index
print(item)

# Output: [4, 5]

Negative index values are also allowed when slicing a collection. Here's an example of omitting the start index and specifying the end as a negative index value to extract the integers 1 and 2:

my_list = [1, 2, 3, 4, 5]
item = my_list[:-3]  # Omit the start index
print(item)

# Output: [1, 2]

One last thing you can do with slicing is specify a step value to select every nth character. The basic syntax for slicing a list with a step value is as follows:

list[start : end : step]

The `list`, `start`, and `end` are the same as defined above, and the `step` is the number of items you want to skip. Here's an example of how you could select every other item from a list:

my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
item = my_list[::2]  # Omit start/end index values
print(item)

# Output: [0, 2, 4, 6, 8]

By omitting the start and end index, we select all items in the list, and the step value selects every two items starting at first.


We can also use negative values for the step, allowing for some interesting behavior. Here's an example of how you can reverse the order of a list with slicing:

my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
item = my_list[::-1]  # Omit start/end index values
print(item)

# Output: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]


Modifying Values in a Python List

Lists are mutable data types, meaning we can add, remove, or modify item values. In the next section, you'll see how to add and remove items from a list. In this section, I'll show you how to modify the existing values already contained within the list.


To modify one existing value, you can use indexing to choose which item should be modified and assign the new value using the equals operator. Below, I show how to change an item's value from `my_list` to something else.

my_list = [1, 2, 3, 4, 5]
my_list[0] = 9  # Change the first item to a 9
print(my_list)

# Output: [9, 2, 3, 4, 5]

You can also change more than one item using the slicing notation discussed above. Here's an example showing how to change the first three numbers to 9, 8, and 7.

my_list = [1, 2, 3, 4, 5]
my_list[0:3] = [9, 8, 7]
print(my_list)

Output: [9, 8, 7, 4, 5]

It's important to note that we set the slice equal to a list. What happens is the items selected by the slice (my_list[0:3]) will be replaced by all items in the assignment list ([9, 8, 7]). In the example above, the slice and assignment list are of equal length. What happens if they are of unequal length? The following code snippets show what happens with fewer items assigned than selected and more assigned than selected.


Fewer assigned than selected
my_list = [1, 2, 3, 4, 5]
my_list[0:3] = [9]
print(my_list)

# Output: [9, 4, 5]

More assigned than selected
my_list = [1, 2, 3, 4, 5]
my_list[0:3] = [9, 9, 9, 9, 9, 9]
print(my_list)

# Output: [9, 9, 9, 9, 9, 9, 4, 5]


Common Functions and Methods to Manipulate Python Lists

Function/Method

Definition

list(iterable)

Converts an iterable to a list

len(iterable)

Returns the number of items in a list

list.append(item)

​Adds an item to the end of the list

list.pop(index=-1)

Removes the item at a specified index and returns it. If no index is provided, it removes and returns the last item in the list

list.remove(item)

Removes the first occurrence of a specified item in the list

list.insert(index, item)

Inserts an item at a specified index in the list

list.sort(key=None, reverse=False)

Sorts the items in the list in ascending order. It can also take an optional key function and a reverse flag to perform a custom sort

sorted(iterable, key=None, reverse=False)

Returns a new sorted list from the items in an iterable. It can also take an optional key function and a reverse flag to perform a custom sort

Note that the "list." in the table is the variable that contains the list you want to manipulate.



Using Python's `list` Function

The `list` function converts an iterable to a list. Below I show how to convert a string to a list.

my_str = "Hello!"
my_list = list(my_str)
print(my_list)

# Output: ['H', 'e', 'l', 'l', 'o', '!']

Using Python's `len` Function

The `len` function takes an iterable as an argument and returns the number of elements within the iterable. In our case, we provide a list (the iterable), and the function will count the total number of items (elements) in the list and return the count. Below is an example of finding the number of integers in a list.

my_list = [1, 2, 3, 4, 5]
length = len(my_list)
print(length)

# Output: 5

Using Python's `append` Method

The `append` method modifies the original list by adding a new item to the very end of the list. Below is an example showing how to add a new integer to the end of a list.

my_list = [1, 2, 3, 4, 5]
print(my_list)
my_list.append(6)  # Add to the list
print(my_list)

# Output before: [1, 2, 3, 4, 5]
# Output after:  [1, 2, 3, 4, 5, 6]

Using Python's `pop` Method

The `pop` method removes an item from a list based on a given index value. Upon removal, that value is also returned. If no index value is specified, the very last item in the list is removed. Below are two examples of removing items from a list, one with a specified index value and one without.

my_list = [1, 2, 3, 4, 5]
removed_value = my_list.pop(2)
print(removed_value)
print(my_list)

# Removed Value: 3
# List: [1, 2, 4, 5]
my_list = [1, 2, 3, 4, 5]
removed_value = my_list.pop()
print(removed_value)
print(my_list)

# Removed Value: 5
# List: [1, 2, 3, 4]

Using Python's `remove` Method

The `remove` method removes an item based on its value. An error is produced if no item is found with the specified value. Below is an example of removing an item from a list of strings:

my_list = ["one", "two", "three", "four", "five"]
my_list.remove("two")
print(my_list)

# Output: ["one", "three", "four", "five"]

Using Python's `insert` Method

The `insert` method inserts a new item at a specified index location within the list. The item is placed at the end of the list if the index is positive and out of range. The item is placed at the beginning of the list if the index is negative and out of range. Below I provide 3 examples, one where the index is in range and two where it is out of range.


In range

my_list = ["one", "two", "three", "four", "five"]
my_list.insert(3, "two")
print(my_list)

# Output: ['one', 'two', 'three', 'two', 'four', 'five']

Out-of-range positive

my_list = ["one", "two", "three", "four", "five"]
my_list.insert(999, "two")
print(my_list)

# Output: ['one', 'two', 'three', 'four', 'five', 'two']

Out-of-range negative

my_list = ["one", "two", "three", "four", "five"]
my_list.insert(-999, "two")
print(my_list)

# Output: ['two', 'one', 'two', 'three', 'four', 'five']

Using Python's `sort` Method

The `sort` method permanently sorts the original list in ascending order. You can sort the list in reverse order by changing the argument to `reverse=True` in the method's parameters. Below are two examples of sorting a list, one ascending and the other descending.

my_list = [3, 6, 4, 7, 1, 5, 2]
my_list.sort()
print(my_list)

# Output: [1, 2, 3, 4, 5, 6, 7]
my_list = [3, 6, 4, 7, 1, 5, 2]
my_list.sort(reverse=True)
print(my_list)

# Output: [7, 6, 5, 4, 3, 2, 1]

Using Python's `sorted` Function

The `sorted` function does not modify the original list. It returns a sorted copy of the list provided. You can sort the list in reverse order by changing the argument to `reverse=True` in the function's parameters. Below are two examples of sorting a list, one ascending and the other descending.

my_list = [3, 6, 4, 7, 1, 5, 2]
sorted_list = sorted(my_list)
print(sorted_list)

# Output: [1, 2, 3, 4, 5, 6, 7]
my_list = [3, 6, 4, 7, 1, 5, 2]
sorted_list = sorted(my_list, reverse=True)
print(sorted_list)

# Output: [7, 6, 5, 4, 3, 2, 1]



3 views0 comments

Recent Posts

See All
bottom of page