Language: EN

python-listas

Lists in Python

A list in Python is an ordered and mutable 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 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 brackets [] and the elements are separated by commas.

Creating a List with Brackets []

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

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

Creating an empty list

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

empty_list = []

Common Operations with Lists

Accessing list elements

The elements of a list can be accessed using numerical indices. The index starts at 0 for the first element and increases 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
sorted_list = 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.

Example of a Nested List

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(nested_list[0][1])  # Result: 2