Python Lists

Python has several data types that let us group items together. Lists are one of the most frequently used and versatile data types. For example, an e-commerce site can use a list to store items added by a user in a cart.

Here's why lists fit this use case:

  • Lists allow us to add, remove and change items. A shopping cart can change.
  • Items in a list are ordered. A shopping cart shows items in the order they are added.
  • Lists allow duplicate values (might not be relevant for a shopping cart, though).

Creating a List

The most common way to create a list is by placing items inside square brackets [], separated by commas. For example,

cart = ["T-shirt", "Lamp", "Pen"]
print(cart)

# A list of mixed data types
my_list = [1, "Python", 3.14]
print(my_list)

# Empty list
my_list = []
print(my_list)

We can also create a list using the list() function. The function converts an iterable (such as strings, range() etc.) into a list. For example,

vowels = "aeiou"

# Convert a string to a list
vowels_list = list(vowels)
print(vowels_list)

Output

['a', 'e', 'i', 'o', 'u']

Accessing List Items

The items in a list are in order and each item is associated with an integer, known as index.

The index of the first item is 0, the index of the second item is 1 and so on.

Index of Python List Items
Index of List Items

We use these indices to access list items. For example,

languages = ["Python", "Swift", "C++"]

# Access the first item
print(f"languages[0] = {languages[0]}")

# Access the third item
print(f"languages[2] = {languages[2]}")

Output

languages[0] = Python
languages[2] = C++

Negative Indexing

Python also supports negative indexing. The index of the last item is -1, the index of the second last item is -2 and so on.

Let's see an example.

languages = ["Python", "Swift", "C++"]

# Access the last item
print('languages[-1] =', languages[-1])

# Access the third last item
print('languages[-3] =', languages[-3]) 

Output

languages[-1] = C++
languages[-3] = Python

We can also extract or update a portion of a list (or any other sequence) easily using the slicing operator :. Learn more on the dedicated tutorial: Python Slicing.


Adding and Updating Items

As mentioned, lists are mutable and we can add and update items of a list.

Updating List Items

We use the = operator to assign a new item to a specified position.

cart = ["T-shirt", "Lamp", "Pen"]

# Update second item to "Shoes"
cart[1] = "Shoes"

print(cart)    # ['T-shirt', 'Shoes', 'Pen']

Adding Items to a List

We can use the append() method to add an item to the end of the list.

cart = ["T-shirt", "Lamp", "Pen"]

# Add "Book" to the list
cart.append("Book")

print(cart)    # ['T-shirt', 'Lamp', 'Pen', 'Book']

If we need to add all the items from another list (or any other iterable), we can use the extend() method.

cart = ["T-shirt", "Lamp", "Pen"]
fav_items = ["Headphones", "Phone"]

# Add all the items from fav_items to cart
cart.extend(fav_items)

print(cart)    # ['T-shirt', 'Lamp', 'Pen', 'Headphones', 'Phone']

We can also insert an item at a specified position, using the insert() method.

cart = ["T-shirt", "Lamp", "Pen"]

# Add "Book" at index 2 (3rd position)
cart.insert(2, "Book")

print(cart)    # ['T-shirt', 'Lamp', 'Book', 'Pen']

Remove Items From a List

There are several methods such as remove(), pop() and clear() that we can use to remove items from a list. The method we use depends on our requirements.

The remove() method removes the specified item from a list.

The pop() method removes and returns the last item (if an index is not provided). This helps us implement lists as stacks (last in, first out data structure).

The clear() method empties a list.

cart = ["T-shirt", "Lamp", "Pen", "Book"]

# Remove "Pen" from the list
cart.remove("Pen")    # ['T-shirt', 'Lamp', 'Book']

# Remove the last item
last_item = cart.pop()
print(cart)   # ['T-shirt', 'Lamp']
print(last_item)    # Book

# Clear the list
cart.clear()
print(cart)    # []

By the way, we can also delete individual items or even the whole list itself using the del keyword.

cart = ['T-shirt', 'Lamp', 'Pen', 'Book']

# Delete the third item (index 2)
del cart[2]
print(cart)    # ['T-shirt', 'Lamp', 'Book']

# Delete the list itself
del cart
print(cart)    # NameError: name 'cart' is not defined

Copying a List

Suppose we have a favorite_items list and we want to copy it to the cart list. If we use the = operator to copy a list, it may feel like it's working but there is an underlying issue. Let's first understand this issue, then we'll learn how to fix it.

favorite_items = ["T-shirt", "Lamp", "Pen"]

cart = favorite_items

# Add an item to favorite_items list
favorite_items.append("Book")

print(f"favorite_items = {favorite_items}")
print(f"cart = {cart}")

Output

favorite_items = ['T-shirt', 'Lamp', 'Pen', 'Book']
cart = ['T-shirt', 'Lamp', 'Pen', 'Book']

In the program, we've added "Book" to the favorite_items. However, this also updates the cart list automatically. This happens because = doesn't make a copy. Instead, assignment makes the cart variable point to the same favorite_items list in memory.

To solve this issue, we use the copy() method.

favorite_items = ["T-shirt", "Lamp", "Pen"]

# Copying a list
cart = favorite_items.copy()

# Add an item to favorite_items list
favorite_items.append("Book")

print(f"favorite_items = {favorite_items}")
print(f"cart = {cart}")

Output

favorite_items = ['T-shirt', 'Lamp', 'Pen', 'Book']
cart = ['T-shirt', 'Lamp', 'Pen']

The copy() method returns a shallow copy of a list. This means the copied list is different from the initial list. Now our program works as expected.


Python List Methods

Python provides us many list methods out of the box, making working with lists very easy. They are accessed as list.method().

We've already used some of the methods above. Here's a complete list of methods:

Method Description
append() Adds an item to the end of the list
extend() Adds all the items from another list (or any other iterable)
insert() Inserts an item at the specified index
remove() Removes the specified value from the list
pop() Returns and removes the last item or item at the given index
clear() Removes all items from the list
index() Returns the index of the first matched item
count() Returns the count of the specified item
sort() Sorts the list in ascending/descending order
reverse() Reverses the list
copy() Returns the shallow copy of a list

The len() Function

Built-in functions such as enumerate(), len(), max(), min(), sorted() etc. are commonly used with lists to perform different tasks. You can find all the built-in functions in Python here.

One built-in function worth memorizing is len(). The len() function returns the number of items in a list.

favorite_items = ["T-shirt", "Lamp", "Pen"]

size = len(favorite_items)
print(size)   # 3

List Membership Test

We can test if an item exists in a list or not, using the in keyword.

cart = ["T-shirt", "Lamp", "Pen"]

result = "Lamp" in cart
print(result)   # True

result = "Book" in cart
print(result)   # False

Iterating Through a List

Since a list is a sequence of items in order, we can iterate a list's items using a for loop.

cart_items = ["T-shirt", "Lamp", "Pen"]

for item in cart_items:
    print(item)
Did you find this article helpful?