How Python Lists Work

How Python Lists Work

A Python List is a built-in, ordered collection of elements or items. Items in a list can be of any data type, including numbers, strings, objects, or even other lists. Lists are versatile and widely used in Python to manipulate, organize, and store data.

A Python list is dynamic and mutable. It means their size will adjust depending on how many elements they contain. And you can edit them after creation by adding or removing items without creating a new list.

In this article, you'll learn how a list is used to manipulate and store data in Python. This guide is beginner-friendly and doubles as a mini-tutorial. Therefore, only a basic knowledge of Python programming language is required to grasp it.

Creating And Initializing Lists

Creating a list in Python is easy. A list is created using square brackets[] and separating the elements with a comma. You can create lists with the same data type, multiple data types, and even empty lists can be created. It is also possible to nest a list inside another list. To create a multi-dimensional list.

For example:

# Creating a list with the same data type
List1 = [5, 10, 15, 20]
print(List1)
# Creating a list with multiple data types
List2 = [5, 'blue', True, 1.5]
print(List2)
# Creating an empty list
List3 = []
print(List3)
# Creating a multi-dimensional list
List4 = [['blue', 'red'], ['bread', 'pasta']]
print(List4)

Output:

# This is a list of numbers
[5, 10, 15, 20]
# This list contains an integer, a string, a boolean, and a float value
[5, 'blue', True, 1.5]
# This is an empty list
[]
# This is a multidimensional list
[['blue', 'red'], ['bread', 'pasta']]

Accessing and modifying List elements

There are two ways to access values or elements in a Python list. They include;

  • Indexing

  • Slicing

Indexing

Indexing starts at 0. It means the first element has an index of 0, the second an index of 1, the third an index of 2, and so on. You can also use a negative index that starts at the last element (-1). Multidimensional lists can be accessed using nested indexes. The index must be an integer. This method is applicable when accessing individual list elements or items.

Slicing

Slicing uses a colon (:) to separate the start and end indices. For this method, you need to specify the start and end indices. It can also be known as Specifying a range. If you omit the start value, the range begins from the first element. If you omit the end value, the range stops at the last element. You can also use negative indices when slicing. This method is useful when accessing a range of list elements or items.

For example:

# Accessing Elements By Indexing
# Accessing a list element using a positive index
List1 = [5, 10, 15, 20]
print(List1[2])

Output: 15

# Accessing a list element using a negative index
List2 = [5, 'blue', True, 1.5]
print(List2[-3])

Output: blue

# Accessing an element from a multidimensional list. Using a nested index
List4 = [['blue', 'red'], ['bread', 'pasta']]
print(List4[0][1])
print(List4[1][0])

Output: red
bread

# Accessing Elements By Slicing
# Accessing a range of elements by slicing
List5 = [2, 4, 6, 8, 10, 12]
print(List5[1:5])

Output: [4, 6, 8, 10]

# Omitting the start value
List5 = [2, 4, 6, 8, 10]
print(List5[:3])

Output: [2, 4, 6]

# Omitting the end value
List5 = [2, 4, 6, 8, 10]
print(List5[3:])

Output: [8, 10]

To modify an element in a list, all you have to do is update the specific element using its index.

For example:

# Modifying a list element
List2 = [5, 'blue', True, 1.5]
List2[1] = 'black'
print(List2)

Output: [5, 'black', True, 1.5]

Note: The first item has an index of 0.

List methods

Python list has methods that help us work with them. This section will take you through the methods, show you how to use them in your code, and describe their functions.

MethodsCodeFunctions
List append()list.append(element)It adds a single element at the end of the list
List extend()list.extend(iterable)It adds iterable elements to the end of the list.
List insert()list.insert(index, element)It adds an element at a specified position.
List remove()list.remove(element)It removes the first occurrence of an element from a list.
List pop()list.pop([index])It removes the element at a specified position. If no element is specified, it removes the last element in the list.
List reverse()list.reverse()It reverses the order of the elements in a list.
List count()list.count(element)It returns the number of times an element appears in a list.
List sort()list.sort()It sorts the elements in a list in ascending order.
List clear()list.clear()It removes all elements in a list.
List copy()list.copy()Returns a copy of the list.
List index()list.index(element[, start[, end]])It returns the index of the first occurrence of an element in a list.

List comprehension

List comprehension is a simple way to define a list in Python. It offers a shorter syntax to create a new list from a pre-existing list. Otherwise, you will have to write a for statement with a conditional test.

A list comprehension consists of the following parts:

  1. Output expression,

  2. Input sequence,

  3. A variable that represents a member of the input sequence and

  4. A predicate expression; is optional.

Explanation:

list = [j ** 2 for j in range(1, 20) if j % 2 == 0]

Here, 'j ** 2' is the output expression, range (1, 20) is the input sequence,
 'j' is the variable,
and 'if j % 2 == 0' is a predicate expression.

For example:

# A program to demonstrate list comprehension in Python
# The list below contains the squares of all even numbers, from range 1 to 20

even_square = [j ** 2 for j in range(1, 20) if j % 2 == 0]
print(even_square)

Output: [4, 16, 36, 64, 100, 144, 196, 256, 324]

# Without list comprehension, the above is the same as
even_square = []
for j in range(1, 20):
if j % 2 == 0:
even_square.append(j**2)
print(even_square)

Output: [4, 16, 36, 64, 100, 144, 196, 256, 324]

Practical examples

This section shows you some practical scenarios where lists can be used.

Example 1: Reverse a list Create a function that takes in a list and returns a list with the reversed order.

* [50, 40, 30, 20, 10] - [10, 20, 30, 40, 50]

* [g, f, e, d, c, b, a] - [a, b, c, d, e, f, g]

Solution:

l_of_n = [50, 40, 30, 20, 10]
l_of_l = ['g', 'f', 'e', 'd', 'c', 'b', 'a']
print(l_of_n[::-1])
print(l_of_l[::-1])

Output: 
[10, 20, 30, 40, 50]
['a', 'b', 'c', 'd', 'e', 'f', 'g']

Example 2: Counting elements

Consider a list of colors where some are missing from their place. Write a function that counts the number of colors present in the list(yes means present).

For example

color= [True,  False,  True,  False, True,  True,  True,  True, True,  False, True,  False, True,  True, False, True, True,  True,  True,  True, False, False, True,  True, True].

The correct answer would be 19

Solution:

color = [True, False, True, False,
True, True, True, True,
True, False, True, False,
True, True, False, True,
True, True, True, True,
True, False, True, True, True]
print(color.count(True))

Output: 19

Conclusion

Python list is a dynamic, versatile, and mutable data structure which provides an ordered collection of elements. It means they can adapt to the number of elements they contain, expand or contract in size when necessary and they can be modified after being created. Their mutable ability is a powerful attribute that enhances flexibility.

This article provides an extensive overview of the various list concepts. Whether you are creating, accessing, or modifying list elements, this guide equips you with the essentials. By understanding the concepts outlined here, even with a basic knowledge of the Python programming language, you can confidently utilize lists for effective data manipulation. As you explore more Python capabilities, lists will remain a fundamental tool.

References