Python – Lists

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.

And when running that code we get the following output:


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.

when running this code we will get the following output:

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.

And when running that code we get the following output:

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.

And when running that code we get the following output:

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.

And when running that code we get the following output:

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.

And when we run this code we will get the output below.


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:

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.

And when running that code we get the following output:

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.

And when running that code we get the following output:

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.

And when running that code we get the following output:

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.

And when running that code we get the following output:

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.

And when running that code we get the following output:

We could have used this code:

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.

And when running that code we get the following output:

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.

And when running that code we get the following output:

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.


So there you have it, with the information learned above you should have enough information to have a good understand of lists in python and how to interact with them. If there was something that I missed or that is unclear feel free to leave a comment asking for clarification.

1 Trackback / Pingback

  1. Python - List Comprehensions - Kyle Kowalczyk

Leave a Reply

Your email address will not be published.