
In this post I will be outlining what a list is and the different things you can do with lists in Python such as recalling elements from lists, modifying lists, and reorganizing lists. The first thing you need to understand is a list is just a structured way of storing and accessing data throughout your program, you can store anything in your list from integers, floats, strings, and even other lists. How you build your lists and how you interact with them throughout your program will be entirely up to you and how you engineer your program, lets get started.
What is a List
In Python a list is an iterable data structure that can be used to store things such as strings, integers, variables, objects, even other lists. Python treats a list is a mutable object, which means that you can change the contents of a list on the fly without needing to make a new list or converting the data type. Lists are a very common data structure in Python and understanding how to interact with them will be vital to creating more complex scripts and programs.
Defining a list
A list in Python is denoted by square brackets “[]” and entries in that list are separated by commas. Below is an example defining a list with 4 different string values.
1 2 3 4 5 |
#!/usr/bin/python3 string_list = ['Henry', 'Ivan', 'Zach', 'Adam'] print(string_list) |
And when running that code we get the following output:
1 2 3 |
user#laptop:~/$ list.py ['Henry', 'Ivan', 'Zach', 'Adam'] user#laptop:~/$ |
Iterate over a list
One very powerful thing you can do with lists is iterate over them, for instance in a for loop. This will allow us to handle each individual element in the list, run a block of code against it, and move onto the next one in the list. Below is an example of iterating over the same list we used above and printing out the element.
1 2 3 4 5 6 7 8 |
#!/usr/bin/python3 string_list = ['Henry', 'Ivan', 'Zach', 'Adam'] for entry in string_list: print(entry) #END |
when running this code we will get the following output:
1 2 3 4 5 6 |
user#laptop:~/$ list.py Henry Ivan Zach Adam user#laptop:~/$ |
We can see that instead of printing the entire list it printed each entry one at a time until it ran out of items in the list.
Getting elements from a list
In the code snipped below I have several print statements that use a technique called slicing that will retrieve specific elements in a list such as, only the first, only the last, only first 2, all elements excluding last element, etc. You can use these techniques to grab elements in an list and do not need to know the total number of elements in the list or the index that relates to each of your elements within the list.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
#!/usr/bin/python3 my_list = ['Henry', 'Ivan', 'Zach', 'Adam'] # Print only first element print( my_list[0] ) # Print only last element print( my_list[-1] ) # Print 3rd element # note here we use the index to recall the element, because the index starts at 0, the 3rd entry is index number 2 print( my_list[2] ) # Print only last 2 elements print( my_list[-2:] ) # Print only first 2 elements print( my_list[:2] ) # Print all elements excluding first element print( my_list[1:] ) # Print all elements excluding last element print( my_list[:-1] ) |
And when running that code we get the following output:
1 2 3 4 5 6 7 8 9 |
user#laptop:~/$ list.py Henry Adam Zach ['Zach', 'Adam'] ['Henry', 'Ivan'] ['Ivan', 'Zach', 'Adam'] ['Henry', 'Ivan', 'Zach'] user#laptop:~/$ |
Looking at the output, each line of output correlates with the print statements in the code. I wont explain each one here as I have comments in the code that explain how each of the slices work but we can see how we can easily grab certain parts of the list by slicing it various ways.
Adding elements to an existing list
You will often need to add new values to a list you already have, to do this you do not need to create a new list or anything crazy, you can just use the ‘append()’ method to add a new value to the end of a list. Below is a snippet of code showing an example.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#!/usr/bin/python3 ''' Add a value to a list ''' my_list = ['value1', 'value2', 'value3', 'value4', 'value5'] my_list.append('My New Value') print( my_list ) |
And when running that code we get the following output:
1 2 3 |
user#laptop:~/$ list.py ['value1', 'value2', 'value3', 'value4', 'value5', 'My New Value'] user#laptop:~/$ |
We can see in line 7 of the code we defined a list with 5 values and in line 9 we used the ‘append()’ method and passed in ‘My New Value’ to append ‘My New Value’ to the end of the list
Lastly when printing out the raw list we see at the end “My New Value” is the 6th value now in the list.
Deleting elements from a list
Along with adding elements you will often delete elements from a list and once again the Python standard library gives us a very trivial way to do this with the ‘remove()’ method. Below I have a snippet of code with an example of that.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#!/usr/bin/python3 ''' Removing an item from a list ''' list = ['value1', 'value2', 'value3', 'value4', 'value5'] list.remove('value2') print(list) #END |
And when running that code we get the following output:
1 2 3 |
user#laptop:~/$ list.py ['value1', 'value3', 'value4', 'value5'] user#laptop:~/$ |
We can see in line 7 I define my initial list, and in line 9 i use the ‘remove()’ method and pass in ‘value2’ which will search the list for ‘value2’ and if it finds it, the value will be removed from the list and lastly we print the entire list to the screen.
When running that code we can see that ‘value2’ is no longer in the list.
Getting the index of an item in a list
Every element in a list has an index location within that list and there are times where you need to reference that index directly to work with that element. The first element in a list will always be 0 and every element after that will have an index that is incremented by 1, so if you have a total of 50 elements in your list, the 50th element will have an idex of 49.
Below I have an example of checking if an element is in a list and printing its index if it is found.
1 2 3 4 5 6 7 8 9 10 11 12 |
#!/usr/bin/python3 ''' Getting the index of an item ''' my_list = ['value1', 'value2', 'value3', 'value4', 'value5'] if 'value4' in my_list: print(my_list.index('value4')) #END |
And when we run this code we will get the output below.
1 2 3 |
user#laptop:~/$ list.py 3 user#laptop:~/$ |
Reversing a list
It is at times beneficial to get the reverse order of your list, for instance if you want to add an entry to the beginning of your list vs the end. Below I have a snippet of code showing an example of how to reverse a list and print it to the screen.
list = [‘value1’, ‘value2’, ‘value3’, ‘value4’, ‘value5’]
And when running that code we get the following output:
1 2 3 |
user#laptop:~/$ list.py ['value5', 'value4', 'value3', 'value2', 'value1'] user#laptop:~/$ |
Looking at the source code we see a lot happening inside that print statement. We passed ‘my_list’ into the ‘reversed()’ method but we didn’t just print that out because we had to pass that as an argument to the ‘list()’ method, then we could print out our reversed list.
Now doing it this way does work but it is getting a bit ugly when looking at the code. Below I have another example that uses a technique I referenced earlier called slicing.
1 2 3 4 5 6 7 8 9 10 11 |
#!/usr/bin/python3 ''' Reversing a list ''' my_list = ['value1', 'value2', 'value3', 'value4', 'value5'] print(my_list[::-1]) #END |
And when running that code we get the following output:
1 2 3 |
user#laptop:~/$ list.py ['value5', 'value4', 'value3', 'value2', 'value1'] user#laptop:~/$ |
As you see we reversed our list exactly like before but in my opinion this looks more clean when reading the code as long as you understand what is going on with the slicing. I’m not sure which one takes longer to compute but most of the time it shouldn’t matter unless your dealing with huge lists and have strict timing requirements so the way I look at is 6 on one side and half a dozen on the other.
Sorting a list
There are also times where you need to sort a list for instance alphabetically or from lowest to highest, below I have a snipped of code that defines 2 lists, one with integers out of order and one with strings out of order alphabetically and I use the ‘sorted’ method to sort that list and print it out.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#!/usr/bin/python3 ''' Sorting a list. Example with integers and strings ''' number_list = [15, 22, 65, 95, 88, 63, 1, 100] string_list = ['Henry', 'Ivan', 'Zach', 'Adam'] print( sorted(number_list) ) print( sorted(string_list) ) |
And when running that code we get the following output:
1 2 3 4 |
user#laptop:~/$ list.py [1, 15, 22, 63, 65, 88, 95, 100] ['Adam', 'Henry', 'Ivan', 'Zach'] user#laptop:~/$ |
We see that the first list that got printed out it took all the integers and sorted them from lowest to highest.
We also can see it took the list of strings and sorted them A to Z.
Checking for an element in a list
It is very easy using an “if” statement to check if a value is contained somewhere inside of your list. Below is the code showing an example checking for a number within a list of numbers.
1 2 3 4 5 6 7 8 9 10 11 12 |
#!/usr/bin/python3 ''' Check if a particular item is in a list ''' list = [1, 2, 3, 10, 4, 5] if 55 in list: print('its in there') else: print('its not in there') |
And when running that code we get the following output:
1 2 3 |
user#laptop:~/$ list.py its not in there user#laptop:~/$ |
Now if we were to change the integer ’55’ within our if statement to the integer 10 we would get the output ‘its in there’. Feel free to copy that code into your python interpreter and play with the value inside the if statement to see how the output changes.
One thing to note if you are working with very large lists if your element is one of the first in the list, using this technique will find it right away but if it is, lets say the last element in a list it will take longer to find it. These wait times are very small (a few ms) but it is good to know if you are dealing writing code that will be very sensitive on execution time.
Get index and value for each element in list
When recalling values in your list it is at times beneficial to know what index number corresponds to each of your elements in the event you need to do something with that specific element. The Python standard library provides us with the ‘enumerate()’ method that will return the index and the value of each element in a list. Below is a snippet of code that demonstrates that.
1 2 3 4 5 6 7 8 9 10 11 12 |
#!/usr/bin/python3 ''' Using enumerate to get the index and the entry ''' my_list = ['Henry', 'Ivan', 'Zach', 'Adam'] for index, entry in enumerate(my_list): print('Index: {} | Item: {}'.format(index, entry)) #END |
And when running that code we get the following output:
1 2 3 4 5 6 |
user#laptop:~/$ list.py Index: 0 | Item: Henry Index: 1 | Item: Ivan Index: 2 | Item: Zach Index: 3 | Item: Adam user#laptop:~/$ |
Looking at the code one thing that may be a bit misleading is that when getting the index and value of each element in the list we do that in the for loop which we do not. The for loop iterates over each element that was returned from the ‘enumerate()’ method so we can print it to the screen for the user or run some code against each element within that for loop and have access to the index value for each element.
Find the number of elements contained in a list
There are times you will need to know the total number of entries you have in your list and to do that the Python standard library provides a very quick way to get that number. It is not only quick to code but it is very quick in terms of cpu time vs using something like a counter variable with a for loop.
1 2 3 4 5 6 7 8 9 10 11 |
#!/usr/bin/python3 ''' Get the length of a list ''' list = ['tony', 'tracy', 'steve', 'frank', 'greg', 'ashley'] print( len(list) ) |
And when running that code we get the following output:
1 2 3 |
user#laptop:~/$ list.py 6 user#laptop:~/$ |
We could have used this code:
12345678910 #!/usr/bin/python3list = ['tony', 'tracy', 'steve', 'frank', 'greg', 'ashley']counter = 0for entry in list:counter += 1print(counter)We will get the exact same result but as I stated earlier this takes much longer to compute so it does not scale well and uses many more lines of code thus being more prone to having the person writing the code introduce a bug.
Joining a list of strings together for output
If you have a list that is compromised of strings you are able to concatenate the strings together using the “join()” method and it will produce you with an entirely new string that is compromised of the entries in your list. The snippet of code below gives an example of that.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#!/usr/bin/python3 ''' Joins a list of strings together into a single string ''' # List containing 5 entries that are strings list = ['value1', 'value2', 'value3', 'value4', 'value5'] # Joins all of the strings together and between them adds the specified string character string = ' | '.join(list) # prints out final string print(string) |
And when running that code we get the following output:
1 2 3 |
user#laptop:~/$ list.py value1 | value2 | value3 | value4 | value5 user#laptop:~/$ |
If we look in the source where I declare the variable ‘string’ the first thing I have before the ‘.join()’ method is a string, and this string is used by join in between your list entries. You can see it does not attach them to the beginning or the end of your string, only in between, now you can use any string and it will still work with the same principal.
The ‘.join()’ method allows a very clean and easy way to do this in one line vs having to create your own function and handle it all yourself.
Nesting lists within lists
This can sound complicated if you are not able to visualize what is happening in your head.
An easy way to thing of it is folders and files in a file cabinet, the files being the entries of a list and the folders being a list object. Imagine you have 2 folders for the 2 vehicles you own, a truck and a car, and in those folders you have maintenance history documents, and registration documents. Now imagine taking those 2 folders (lists) with all of the files (entries) in them and putting them both inside a “master” folder that you call ‘vehicle information’. That is essentially exactly what you are doing when you nest lists within other lists, with that fresh in your mind lets look at the code below as an example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#!/usr/bin/python3 ''' Create a nested list ''' # creates an empty 'master' list master_list = [] # defines our 'sub lists' sky_list = ['sky', 'blue'] grass_list = ['grass', 'green'] # appends each list inside of the master list master_list.append(sky_list) master_list.append(grass_list) # prints the raw lists, then a line, then each of the lists within the master list print(master_list) print('-' * 10) for list in master_list: print(list) #END |
And when running that code we get the following output:
1 2 3 4 5 6 |
user#laptop:~/$ list.py [['sky', 'blue'], ['grass', 'green']] ---------- ['sky', 'blue'] ['grass', 'green'] user#laptop:~/$ |
Analyzing the source code:
In line 8 I create an empty list that will be my master list.
In lines 11 & 12 I create 2 smaller lists that I will later nest.
In lines 15 and 16 I append my small lists I just created onto the end of my previously empty ‘master_list’.
In line 19 I display the entire contents of ‘master_list’ to show you how it treats each of those smaller lists just as entries.
and lastly in the for loop at lines 21 and 22 I loop through each entry (list) in my master_list and print each of them out. This would be how we could access each of those nested lists.
Analyzing the output:
As we can see our first line is our ‘master_list’ and we can see how it stores the sublists as entries within its own list no different than how it would store an integer, string, or float.
And below our break line we can see how we can iterate over those lists individually so if you needed to modify those sublists you could do it from within that for loop.
List Comprehensions
I have a post dedicated entirely to list comprehensions click here to read that article. In short list comprehensions are used to reduce code and increase efficiency when generating lists from lists.
Leave a Reply