Extracting Elements from a List in Python
To extract an element from a list, write the list's name followed by the element's position in square brackets [ ].
listname[position]
The positions in a list of n elements start at zero and go up to n-1.
So, to extract the first element, you would write listname[0], for the second element listname[1], for the third listname[2], and so on.
What happens if an element doesn't exist?
If you try to access a non-existent element in the list, the interpreter will display an Index error message.
How to Extract the Last Element of a List
To get the last element of a list without knowing its position, use -1 as the index.
listname[-1]
The Python interpreter will traverse the list to the end and return the last element.
To get the second-to-last element, use [-2], the third-to-last [-3], and so on.
This method is known as slicing.
A Practical Example
Given the following list:
year = [2010, 2011, 2012]
To display the last element of the list, you would write:
print(year[-1])
This command outputs the last value in the list:
2012
To display the second-to-last element, you would write:
print(year[-2])
This command outputs:
2011
How to Extract Multiple Elements from a List
In Python, you can also extract two or more contiguous elements from a list.
Just specify the position of the first and last elements to extract, separated by a colon.
list[first_position:last_position]
A Practical Example
Given the list:
year = [2010, 2011, 2012, 2013, 2014]
To display the first three elements, you would write:
print(year[0:3])
This command outputs the first three elements:
[2010, 2011, 2012]
The list boundaries can also be omitted.
The previous command can be written as:
print(year[:3])
The result is the same:
[2010, 2011, 2012]
To display the last three elements, use a negative index starting from -3:
print(year[-3:])
This command outputs the last three elements of the list:
[2012, 2013, 2014]
This operation is also known as slicing.
How to Extract and Remove Elements from a List
To extract and remove one or more elements from a list, use the pop method.
listname.pop(index)
The pop method extracts and removes the specified element.
If no index is specified, pop extracts and removes the last element in the list.
listname.pop()
A Practical Example
The list year consists of the following elements:
year = [2010, 2011, 2012, 2013, 2014]
Using the pop method, extract and simultaneously remove the first element:
print(year.pop(0))
The print statement outputs the value of the first element:
2010
Now, the list consists of the following elements:
[2011, 2012, 2013, 2014]
The first element (2010) is no longer in the list.