1. python
  2. /basics
  3. /lists

Introduction to Python Lists

What are Lists in Python?

Lists are a built-in data structure that allows us to store a collection of items. The elements in a list have a specific order, and since lists are mutable, we can add, remove or change them. Moreover, Python lists can contain elements of different data types, including numbers, strings, booleans, and even other data structures. They're defined using square brackets, with each element separated by a comma.

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

Above, we created a list called nums containing 5 integers.

Creating a List

As we already saw, to create a list in Python we use square brackets and separate the elements with commas. Moreover, we can assign it to a variable with proper naming, so we can do additional manipulation later on.

names = ["Alice", "Bob", "Charlie"]

So, we created a list called names containing three distinct strings.

However, lists can also contain elements of different data types, like so:

data = [1, "two", True,]

print(type(data[0])) # Output: <class 'int'>
print(type(data[1])) # Output: <class 'str'>
print(type(data[2])) # Output: <class 'bool'>

Accessing List Elements

In our previous examples, we accessed and check the type of elements that the list contained. In Python, lists are zero-indexed, meaning that the first item has an index of 0, the second item has an index of 1, and so on. We gain access to the elements with the list's name followed by the index of the element in square brackets.

names = ["Alice", "Bob", "Charlie"]

print(names[1])

# Output: Bob

The output is the name "Bob" since it's the second element in the list and has an index of 1.

Additionally, we can also use the built-in len() function to find the number of elements that the list contains.

names = ["Alice", "Bob", "Charlie"]
print(len(names))

# Output: 3

Iterating Through a List

Lists are iterable and looping over them would probably be something we'll encounter a lot. We can go through their elements by using a for loop or other approaches that Python provides at our disposal.

Let's illustrate:

nums = [1, 2, 3, 4, 5]
for num in numbers:
    print(num)

The output is as follows:

1
2
3
4
5

We encourage you to find out more about loops in our Control Flow Basics in Python - A Guide to Loops article.

Python List Comprehension

List comprehensions are a neat and flexible approach to list creation. We can use a combination of syntax with the for loop and an if statement to generate new elements based on existing ones.

Let's say we have an existing list of numbers and we want to create a new one with the cubes of only the even numbers.

We can start by creating the original list:

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Next, we can use a list comprehension to generate the cubes of the even numbers:

even_cubes = [x**3 for x in numbers if x % 2 == 0]

Finally, we can print and show the new list with cubes of only the even numbers from the original list.

print(even_cubes)

# Output: [8, 64, 216, 512, 1000]

Using the list() Constructor

We can also create lists by using the list() constructor. Moreover, we can create it from any iterable object, such as a string, a tuple, or another list.

Below, we have a string of shopping items separated by commas and we need to tuck them into a list as individual items. Using the list() constructor, we can do this in a single line of code:

shopping_list = "bananas, apples, oranges, bread, milk"
items = list(shopping_list.split(", "))
print(items)

# Output: ['bananas', 'apples', 'oranges', 'bread', 'milk']

Adding Elements to a List

If we wanted to add more elements to our existing list, we can leverage the append() method.

names = ["Alice", "Bob", "Charlie"]
names.append("David")
print(names)

# Output: ["Alice", "Bob", "Charlie", "David"]

Note that the outputs show the item "David" added to the end of the list, showcasing how the append() method works.

Removing Elements from a List

Logically, at times we'll need to remove elements from lists. To do that, we can use the pop(), and remove() methods, just to name a few. There are some nuances to this so let's illustrate them.

If we were to use the pop() method without specifying the index, it removes the last item in the list by default.

names = ["Alice", "Bob", "Charlie"]
names.pop()
print(names)

# Output: ["Alice", "Bob"]

Alternatively, we can also use the remove() or del() methods to specify which element we want to be removed.

names = ["Alice", "Bob", "Charlie"]
names.remove("Bob")
print(names)
names = ["Alice", "Bob", "Charlie"]
del names[1]
print(names)

The output would be the same since the first function specifies the string, and the second removes it by index.

# Output: ["Alice", "Charlie"]

To clear the list of its elements, and leave the list empty we can use the clear() method.

names = ["Alice", "Bob", "Charlie"]
names.clear()
print(names)

# Output: []

List Slicing

As you might have already noticed, Python offers us a lot of neat methods to manipulate lists. Moving forward, we can extract a portion of a list by inserting the list's name in square brackets accompanied by the slicing syntax.

nums = [1, 2, 3, 4, 5]
print(numbers[:3])

The output would be [1, 2, 3], showing that we have extracted the first three elements of the list.

Also, we can extract elements from the end of the list using negative indices.

nums = [1, 2, 3, 4, 5]
print(numbers[-3:])

Now, the output would be [3, 4, 5], since we extracted the last three items of the list.

Sorting Elements in a List

By default, the sort() method sorts elements in a list in ascending order, in a case-sensitive manner.

names = ["Charlie", "Bob", "Alice"]
names.sort()
print(names)

So, the output would be ["Alice", "Bob", "Charlie"], showing that the items in the list have been sorted in ascending order.

Aside from sorting the list alphanumerically, we can do the same with numbers in ascending order.

Let's use the nums list from our previous examples to illustrate:

numbers = [5, 2, 1, 4, 3]
numbers.sort()
print(numbers)

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

To do the opposite, and achieve a descending order, we can specify an argument in the sort function, like so:

numbers = [5, 2, 1, 4, 3]
numbers.sort(reverse=True)
print(numbers)

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

Additional Resources

Data Structures in Python

Sequence Types in Python