List
If you want to know how to create lists, access elements within lists, manipulate lists, and perform common operations such as sorting, filtering, and transforming, this article is for you. Whether you're a beginner or an experienced programmer, this article provides a comprehensive guide. The step-by-step instructions for Python lists and clear explanations make it easy to understand and apply the concepts.
A list is, normally, any collection of values. The rules of how to add or remove elements from that list can change from one programming language to another. But – generally – they are the only ways for developers to create elements. Lists are not the only way we have to store multiple values at once, but it is the most used tool for that purpose. For example: a list of students, a list of artists, a list of transactions... anything!
This primitive data-type does a lot more stuff than the others.
Every list has the same basic concepts:
The items: are the actual values inside in each position of the list.
The length: is the size of the list (how many items the list has).
Index: is the position of the element.
☝ List positions start a zero (0); the first element is the element in the position zero (0)
These are different examples of list declarations:
1my_empty_list = [] # Empty list 2my_list = ["Apple", "Orange", "Donkey"] # The only way to declare a "list" - a mutable and ordered collection of items 3my_tuple = ("Apple", "Orange", "Donkey") # This is a "tuple" - a more limited, ordered, but immutable collection of items 4my_set = {"Apple", "Orange", "Donkey"} # This is a "set" - a more limited, unordered and immutable collection of items
To access a specific element in a list, you need an index
. We call index
the integer value that represents the position of the element you want to access/get/retrieve.
The index must always start at zero (0). That means that a List of 2 items can have index=0
or index=1
. Trying to get index=2
will return an IndexError
because it will mean that we are trying to access the third element (which does not exist). For example, to get any items in a list you can do the following:
1print(my_list[0]) # Prints the 1st element on the console 2 3aux = my_list[3] 4print(aux) # Prints the 4th element on the console 5 6print(my_list[len(my_list) - 1]) # Prints the last element on the console 7print(my_list[-1]) # Also prints the last element on the console
If you want, you can reset or update any item inside a list using its index, like this:
1my_list[5] = 'Whatever value' 2# Assign a value to the 6th element on the list
append
in Python ListsThe first way is to add the element to the end of the list. You should use this method every time you can because it's a lot faster than insert
.
1my_list = ['Pedro', 'Juan', 'Maria'] 2my_list.append('Chris') # Adds Chris to the end of the list 3print(my_list) # Output: ['Pedro', 'Juan', 'Maria', 'Chris']
insert
in Python ListsUsing insert is easier for the developer because it will let you pick the positions in which you want to insert the element, but it is a slower method (worse performance):
1my_list = ['Pedro', 'Juan', 'Maria'] 2my_list.insert(1,'Chris') # Adds Chris between Pedro and Juan 3print(my_list) # Output ['Pedro', 'Chris', 'Juan', 'Maria']
Python has many ways to delete an element from a list.
pop
It will remove the last element only!
1my_list = ['Pedro', 'Chris', 'Juan', 'Maria'] 2my_list.pop() 3print(my_list) # Output ['Pedro', 'Chris', 'Juan']
remove
It will let you remove the first occurrence of an element by its name.
1# If you want to delete 'Chris', you need to do the following: 2my_list = ['Pedro', 'Chris', 'Juan', 'Maria', 'Chris'] 3my_list.remove('Chris') 4print(my_list) # Output ['Pedro', 'Juan', 'Maria', 'Chris']
delete
It will allow you to delete many items at once, you have to specify the starting position and ending position.
1my_list = ['Pedro', 'Chris', 'Juan', 'Maria', 'Pepe', 'Mario', 'Bob'] 2del my_list[2:5] # This statement deletes the items at indexes 2, 3 and 4 3print(my_list) # Output ['Pedro', 'Chris', 'Mario', 'Bob']
Normally, when you manipulate lists, you have to loop all the items. For example: order them manually, flip them, filter them, etc.
There are many ways you can loop an entire list, but the most used one is the for
loop.
1my_list = [3423, 5, 4, 47889, 654, 8, 867543, 23, 48, 56432, 55, 23, 25, 12] 2for number in my_list: 3 print(number)
Sometimes it is useful to loop the array using each element's position (index). We can do that by using the range()
function.
By default, the range
will start from index zero and continue until a specified number is reached, not including that index number:
1my_list = ['Pedro', 'Chris', 'Mario', 'Bob'] 2 3# The range will cut off before len(my_list) is reached, and therefore we don't need to write (len(my_list)-1) 4for i in range(len(my_list)): 5 print("The positions is " + str(i) + " for the element " + my_list[i]) 6 7### Output: 8# The positions is 0 for the element Pedro 9# The positions is 1 for the element Chris 10# The positions is 2 for the element Mario 11# The positions is 3 for the element Bob
It is also possible to specify the starting index in the range, as well as the increment, by adding a starting point (the first parameter), and an increment value (the last parameter) in the range
method:
1my_list = ['Pedro', 'Chris', 'Mario', 'Bob', "Greg", "Kyle"] 2 3for i in range(1, 6, 2): # range(start value, end value (non inclusive), increment value) 4 print("The positions is " + str(i) + " for the element " + my_list[i]) 5 6### Output: 7# The positions is 1 for the element Chris 8# The positions is 3 for the element Bob 9# The positions is 5 for the element Kyle
You can read more related articles at 4Geeks and keep on the Geek side!