What are Python Lists?
Now the only place where this analogy breaks down is that you can add any type of item that can be placed into the list and any number of items can be put into the list as well. You can even add a list within a list to have a nested list. Theoretically, this could go on forever, but in terms of speed and efficiency of your code the more times you nest a list within another it makes it more difficult to get to that data within the nested list(s). Python lists can contain several different types of items in a single list. For example, a single list could contain a list, a string, and an integer, or any other combination of items.
In this article:
- How to create a python list
- python list methods:
- Accessing items
- Adding/Deleting items
- Changing an item
Lists are super simple to create. All you need is the name of the list to equal the items in the list separated by commas, surrounded by brackets. Now lets imagine that Tim goes birding and identifies 3 species on his walk. The Blue Jay, House Sparrow, and Peregrine Falcon. He can put these 3 species into a list below:
birds = ['Blue Jay', 'House Sparrow', 'Peregrine Falcon']
In this first example, I made a python list of strings (names of each species); however, I could also make a list of integers as well. Thus, continuing with our example, Tim sees the following counts for each bird species, 4 Blue Jays, 20 House Sparrows, and 1 Peregrine Falcon:
count = [4, 20, 1]
I can also combine these two python lists into a single nested list in 2 ways. I can either type both lists out like the following:
bird_count = [['Blue Jay', 'House Sparrow', 'Peregrine Falcon'], [4, 20, 1]]
(Even when separating 2 lists within a list, I still only separate them using a comma.)
or we can use the variables that we had made previously and save them to the new python list bird_count:
bird_count2 = [birds] + [count]
Notice the positioning of the brackets in the above code. Without the brackets adding the two python lists together will create a single list that holds all of the values of each list.
Accessing items within python lists
Now let’s say that I wanted to return just the first item on the list (‘Blue Jay’). The only way to do this with a list is by using the index (remember, all indices start with zero!) inside of brackets [ ] right after the name of the list:
With a list you are also able to call the same item by using negative indices. Since we have 3 items, we can return ‘Blue Jay’ by using an [-3] inside the brackets. With negative indices it starts with -1 being the last item in the list. This picture describes it well:
To return more than one value in a list, you can use list slicing. Let’s say that Tim didn’t want to include the bird of prey in his list. To do so, he can use the following:
When slicing a list, it returns up to, but not including the number after the colon. As in the above example, items at index 0 and index 1 are returned, but not index 2 (Peregrine Falcon).
Adding Items to Python Lists
After Tim created his initial list, he soon realizes that he forgot about another species that he saw during his birding walk. It is extremely simple to add another item to Tim’s list depending on how Tim would like the resulting list to be formatted. In this case, since Tim is just adding a single item to the list that he had forgotten, the easiest method is just to append it to the list using one of the following:
- .insert(index, object)
birds + ['Cardinal']birds.append('Cardinal')birds.insert(4, 'Cardinal')birds.extend(['Cardinal'])
If order matters in your list, using the .insert() method is the method of choice since you can specify at which index you would like the item to go in the list.
Notice that when adding an item using the “+” operator, the item must be in a list itself in order for the command to work properly. However, either method gives the same result when adding only one item to your list. There are subtle differences to be aware of between these two ways of adding an item to your list. The python list .append() and .insert() methods overwrite the birds’ list with the new list that includes the added item. Using the “+” operator does not do this, if you want the item to be added to the list you must then save the line into the “birds” variable:
birds = birds + ['Cardinal']birds += ['Cardinal']
Let’s say that Tim wants to add more than one item to his list because he forgot to add not only “Cardinal” but also “Chipping Sparrow”.
When adding more than one item to a list, you have the choice between 4 different methods. Each of the previous methods can be used along with .extend(iterable). The iterable inside can be a list.
With these 4 methods there are two pairs that will produce the same result:
The .append() and .insert() methods will produce nested lists, while the “+” and .extend() methods will add the items in the new list to the existing list. However, there is one difference between the “+” operator and the .extend() method. The .extend() method will change the original list.
birds.append(['Cardinal', 'Chipping Sparrow']) birds.insert(4, ['Cardinal', 'Chipping Sparrow'])
birds + ['Cardinal', 'Chipping Sparrow'] birds.extend(['Cardinal', 'Chipping Sparrow'])
Deleting Items from Python Lists
Later, Tim learns that House Sparrows are an invasive species that are competing with one of his favorite species (Eastern Bluebirds) for nest-boxes and driving down the Bluebird population levels. He hates the idea of including them on his list and in a fit of rage he wants to remove them from his list.
He has several options to remove that wretched House Sparrow from his list:
- reassigning item to an empty list
# House Sparrow is located at index 1 del birds
del is an effective way to delete the item in the list. You can also delete the entire list with this keyword.
The .remove() method will remove only the first item in the list that has the value specified within the parentheses. For example, if Tim had “House Sparrow” twice in his list, only the first “House Sparrow” would be removed from the list. If he wanted to remove the second “House Sparrow” in his list he could consider reversing the order of the list using the .reverse() method and then using the .remove() method. However, an easier method might be to use any of the other ones of these 4 methods to delete the second “House Sparrow” item in the list.
popped = birds.pop(1) print(popped) birds
This method can be useful if you still want to keep the item in the list to use later, but no longer want it in the list. The .pop() method will remove and return the item at the index specified, so if you have it equal a variable, you can then use your popped item later as seen above with the “popped” variable I created.
birds[1:2] = 
Although with this method it appears that I am slicing out 2 items, I am only removing “House Sparrow” since when slicing Python does not include the last index, but does everything less than that index.
Changing an Item in Python Lists
Tim just wants to replace the House Sparrow with a Cardinal that he saw during his walk as well. This can be easily done by having the slice of the item replaced by another item instead.
birds = 'Cardinal'
Thank you for reading!
Still confused? Contact me to schedule a consultation to get control of your data.
Check out Part 2 of the Series on Tuples here.
Check out Part 3 of the Series on Dictionaries here.
This article was originally posted on Medium.