Skip to content

An Introduction to Lists in Python

Updated: at 03:23 AM

Lists are one of the fundamental data structures in Python used to store ordered collections of elements. Unlike strings which contain ordered sequences of characters, lists can hold elements of any data type including integers, floats, strings, and even other lists. Lists are very versatile and have many uses in Python programming.

In this comprehensive guide, we will cover the basics of Python lists including creation, indexing and slicing, common properties and operations, built-in functions, and mutability. We will also go over real-world applications and examples of using lists in Python. Let’s get started!

Table of Contents

Open Table of Contents

Creating Lists in Python

Python lists can be created by enclosing elements inside square brackets []. Elements are separated by commas. For example:

primes = [2, 3, 5, 7]
fruits = ['apple', 'banana', 'mango']
mixed = [10, 'hello', 3.4]

Lists in Python can hold elements of any data type, be it integers, strings, floats, or a combination of different types. And they need not be homogeneous always.

Initializing an Empty List

We can initialize an empty list in Python simply with empty brackets.

empty_list = []

Using the list() Constructor

The list() constructor can also be used to initialize an empty list or convert another sequence like string, tuple, etc. into a list.

# Empty list
empty_list = list()

# From a string
chars = list('Hello') # ['H', 'e', 'l', 'l', 'o']

# From a tuple
tuple_ = (1, 2, 3)
list_from_tuple = list(tuple_) # [1, 2, 3]

Indexing and Slicing Lists in Python

Lists in Python are indexed and sliced the same way as strings. The index starts from 0 for the first element and goes on to len(list) - 1 for the last element. We can access individual elements using square bracket notation list[index].

fruits = ['apple', 'banana', 'mango']

print(fruits[0]) # 'apple'
print(fruits[1]) # 'banana'
print(fruits[2]) # 'mango'

Trying to access an index outside the bounds will result in an IndexError.

Slicing lists returns a new list containing the sliced elements. The slice has the syntax [start:stop:step].

fruits = ['apple', 'banana', 'mango', 'orange']

fruits[1:3] # ['banana', 'mango'] - elements 1 upto 3-1=2
fruits[0:4:2] # ['apple', 'mango'] - every alternate element

If start index isn’t defined, slicing starts from the first element. If stop index isn’t defined, slice goes till the end of the list. The step index defaults to 1 if not provided.

fruits[:3] # ['apple', 'banana', 'mango']
fruits[1:] # ['banana', 'mango', 'orange']
fruits[::1] # ['apple', 'banana', 'mango', 'orange'] - default step of 1

Negative indices can be used for slicing lists as well, which starts counting from the end of the list.

fruits = ['apple', 'banana', 'mango', 'orange']

fruits[-3:-1] # ['banana', 'mango']
fruits[-3:] # ['banana', 'mango', 'orange']

Common List Properties and Operations

Now that we have seen how to create and index lists in Python, let us go through some common properties and operations related to lists.

Finding Length of List

We can find the length of a list by using the len() function:

fruits = ['apple', 'banana', 'mango']
length = len(fruits)
print(length) # 3

Checking if Element Exists in List

We can check if a particular element exists in the list or not using the in keyword:

fruits = ['apple', 'banana', 'mango']

print('apple' in fruits) # True
print('strawberry' in fruits) # False

Concatenating and Multiplying Lists

Lists in Python can be concatenated using the + operator:

list1 = [1, 2, 3]
list2 = [4, 5, 6]

list3 = list1 + list2 # [1, 2, 3, 4, 5, 6]

They can also be multiplied by an integer value using the * operator:

fruits = ['apple', 'banana', 'mango']

fruits_twice = fruits * 2
# ['apple', 'banana', 'mango', 'apple', 'banana', 'mango']

This repeats the elements in the list as many times as the multiplier.

Counting Occurrences of Element

We can count how many times an element occurs in the list using the count() method:

numbers = [1, 2, 3, 2, 1, 5]

print(numbers.count(1)) # 2
print(numbers.count(3)) # 1
print(numbers.count(4)) # 0 - element doesn't exist

Reversing a List

To reverse the elements of a list in-place we can use the reverse() method:

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

print(numbers) # [5, 4, 3, 2, 1]

Finding Index of Element

We can find the index of the first occurrence of an element using the index() method:

fruits = ['apple', 'banana', 'mango', 'apple']

print(fruits.index('apple')) # 0
print(fruits.index('mango')) # 2

If the element doesn’t exist in the list, this raises a ValueError.

These are some of the basic yet widely used list operations and properties in Python. Let’s now look at some more operations by using built-in methods for lists.

Built-in List Methods in Python

Python provides a variety of built-in methods to carry out common useful operations on lists with ease. We will take a look at some of them here.

Adding Elements

fruits = ['apple', 'banana']

print(fruits) # ['apple', 'banana', 'orange']

fruits.insert(1, 'cherry')
print(fruits) # ['apple', 'cherry', 'banana', 'orange']

fruits.extend(['grape', 'mango'])
print(fruits) # ['apple', 'cherry', 'banana', 'orange', 'grape', 'mango']

Removing Elements

fruits = ['apple', 'banana', 'cherry', 'banana']

print(fruits) # ['apple', 'cherry', 'banana']

print(fruits) # ['apple', 'banana']

print(fruits) # [] - empty list

Sorting a List

numbers = [3, 2, 5, 1]

print(numbers) # [1, 2, 3, 5]

numbers = [3, 2, 5, 1]
sorted_nums = sorted(numbers)
print(numbers) # [3, 2, 5, 1] - unchanged
print(sorted_nums) # [1, 2, 3, 5]

By default sorting is done in ascending order. We can pass reverse=True to sort in descending order.

numbers.sort(reverse=True) # [5, 3, 2, 1]
sorted_nums = sorted(numbers, reverse=True) # [5, 3, 2, 1]

More Methods

Some other useful built-in methods include:

fruits = ['apple', 'banana', 'cherry', 'apple']

fruit_copy = fruits.copy()

print(fruits.index('cherry')) # 2

print(fruits.count('apple')) # 2

print(fruits) # []

This covers some of the commonly used built-in methods for lists in Python.

Lists are Mutable in Python

One key difference between lists and strings is that lists are mutable in Python. Mutability refers to the ability to modify the value of an object after it has been created.

Lists are mutable - we can modify lists after creation by:

For example:

fruits = ['apple', 'mango', 'banana']

# Appending a new element

# Removing an element

# Modifying an element
fruits[0] = 'cherry'

print(fruits) # ['cherry', 'banana', 'orange']

Whereas strings are immutable in Python - their individual characters cannot be changed once created.

This mutability of lists becomes a powerful feature that allows modifying them after creation. It sets them apart from other ordered sequence data structures like strings and tuples in Python.

Real World Examples - List Usage

Now that we have seen the basics of lists in Python, let’s look at some real world examples that illustrate common uses of lists:

1. Grocery List

Let’s create a grocery list by adding all the items we need to buy from the market:

grocery_items = [] # empty to start

# Adding items

# ['Milk', 'Eggs', 'Butter', 'Apples', 'Sugar']

# Removing bought items

# ['Milk', 'Apples', 'Sugar']

Here we started with an empty list and kept adding items we needed to buy. Later we removed items already purchased. This demonstrates real-world mutability and dynamics of Python lists.

2. Student Database

Lists can be used to represent multiple records in a simple database. For example, we can create a students list containing elements as dictionaries holding details like roll number, name, marks, etc.

# Student details database
students = [
  {'roll': 101, 'name': 'Jack', 'marks': 80},
  {'roll': 102, 'name': 'Mary', 'marks': 90},
  {'roll': 103, 'name': 'John', 'marks': 85}

# Accessing student details
# {'roll': 101, 'name': 'Jack', 'marks': 80}

# Mary

# Modifying details
students[2]['marks'] = 75

# 75

This demonstrates how lists are useful for grouping related data sets and modifying them.

3. To-Do List

A simple to-do list can be implemented using a Python list:

todos = ['Finish project', 'Call mom', 'Buy groceries']

# Check off first item

# Add new item
todos.append('Sign up for course')

# ['Call mom', 'Buy groceries', 'Sign up for course']

Here we are adding tasks to a to-do list and removing them when done. This shows a real-world mutable list in action.

4. Stack Implementation

Lists can be used to implement stacks which follow LIFO (Last In First Out) order. We can push to and pop from the end of list to simulate a stack:

stack = []

# Pushing items onto stack

# Popping item off stack
x = stack.pop()

print(stack) # [1, 2]
print(x) # 3

The last item pushed is removed first following LIFO order. This demonstrates lists mimicking the stack data structure.

There are many more such applications of Python lists like implementing queues, histograms, etc. where their dynamic nature and ease of use makes them quite handy.


To summarize, here are some key points about Python lists:

With this comprehensive guide, you should have a good understanding of the basics of lists in Python. They are a versatile built-in data type that is an essential part of Python programming. Lists provide an efficient way to work with ordered collections of data.