Lists are one of the most commonly used data structures in Python. A list is a collection of items that are ordered and changeable. Lists are denoted by square brackets and can contain any type of data, including other lists.
Here’s an example of creating a list of integers:
my_list = [1, 2, 3, 4, 5]
Accessing and manipulating list elements
We can access individual elements of a list by using their index number. The index of the first element is 0, the second element is 1, and so on. We can also use negative indexing, where -1 refers to the last element, -2 refers to the second-to-last element, and so on.
Here’s an example of accessing and manipulating list elements:
my_list = [1, 2, 3, 4, 5] print(my_list[0]) # Output: 1 print(my_list[-1]) # Output: 5 my_list[0] = 6 print(my_list) # Output: [6, 2, 3, 4, 5] my_list.append(6) print(my_list) # Output: [6, 2, 3, 4, 5, 6]
In this example, we accessed the first and last elements of my_list
, changed the value of the first element to 6, and appended a new element with the value 6 to the end of the list.
Slicing lists
We can also access a range of elements in a list using slicing. Slicing is denoted by using a colon between the start and end indices. The slice will include all elements from the start index up to but not including the end index.
Here’s an example of slicing a list:
my_list = [1, 2, 3, 4, 5] print(my_list[1:4]) # Output: [2, 3, 4]
In this example, we sliced my_list
to get a new list containing the elements with indices 1, 2, and 3.
List methods
Python provides a variety of built-in methods for working with lists. Here are some examples:
append()
: Add an element to the end of the listinsert()
: Insert an element at a specified indexremove()
: Remove the first occurrence of an element from the listpop()
: Remove and return an element from a specified indexsort()
: Sort the list in ascending orderreverse()
: Reverse the order of the elements in the list
Here’s an example of using some of these methods:
my_list = [3, 2, 1, 4, 5] my_list.append(6) print(my_list) # Output: [3, 2, 1, 4, 5, 6] my_list.insert(0, 0) print(my_list) # Output: [0, 3, 2, 1, 4, 5, 6] my_list.remove(3) print(my_list) # Output: [0, 2, 1, 4, 5, 6] popped_element = my_list.pop(3) print(my_list) # Output: [0, 2, 1, 5, 6] print(popped_element) # Output: 4 my_list.sort() print(my_list) # Output: [0, 1, 2, 5, 6