Language: EN

python-listas

Lists in Python

A list in Python is a mutable and ordered collection of elements (Mutable means that the elements of a list can be modified after the list is created).

Lists are one of the most versatile and widely used data structures. They allow us to store ordered collections of elements, such as numbers, strings, or other objects.

Characteristics of Lists:

  • Mutability: The elements of a list can be modified after the list is created
  • Ordered: The elements of a list are ordered and maintain the order in which they were added
  • Can contain any data type: A list can contain elements of different data types, such as integers, strings, floats, or other lists

Creating a list

Lists are defined using square brackets [] and the elements are separated by commas.

Create a list with square brackets []

In this example, my_list is a list that contains the numbers from 1 to 5.

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

Create an empty list

It is also possible to create empty lists and subsequently add elements as needed.

empty_list = []

Common operations with lists

Accessing elements of a list

The elements of a list can be accessed using numeric indices. The index starts at 0 for the first element and increments consecutively.

my_list = [10, 20, 30, 40, 50]

print(my_list[0])  # Result: 10
print(my_list[2])  # Result: 30

Adding elements

Lists in Python have several built-in methods for adding elements,

my_list.append(60)  # Adds 60 to the end of the list
my_list.insert(2, 25)  # Inserts 25 at position 2

Concatenating lists

Operations such as concatenating lists or multiplying by an integer can be performed. For example,

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

concatenated_list = list1 + list2  # concatenated_list is [1, 2, 3, 4, 5, 6]
repeated_list = list1 * 3  # repeated_list is [1, 2, 3, 1, 2, 3, 1, 2, 3]

Removing elements

Lists in Python have several built-in methods for removing elements,

my_list.remove(20)  # Removes the value 20 from the list
my_list.pop(3)  # Removes and returns the element at position 3
del my_list[1]  # Removes the element at position 1

Sorting

Lists in Python have several built-in methods for sorting elements,

my_list.sort()  # Sorts the list in ascending order
my_list_sorted = sorted(my_list)  # Creates a new sorted list

Length

Lists in Python have a built-in function to get their length,

length = len(my_list)  # Returns the length of the list

Nested lists

In Python, it is possible to have lists within lists (this is known as nested lists or multidimensional lists).

For example like this,

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

print(nested_list[0][1])  # Result: 2