Categories
Python

Python Lists: A Data Collection Type (Part 1 of 3)

In this post, I will be going through 1 of the 3 built-in data types in python used to store collections of data: Python Lists. (See python tuples and dictionaries)

What are Python Lists?

There are so many different analogies to describe what a python list is and how it is useful. One of the ways that I have used while helping teach kids to code online with Codeverse was comparing it to a resizable drawer in a file cabinet.

The drawer is resizable because the list is only as long as the number of items in it. For example, a list with 20 items has a length of 20, but another list could have 2,000 items. It is also like a file cabinet because you can place items into the list either in front or behind the current item in the list.

The awesome thing is that the programming language (in this case Python) will keep track of the order that every object is in the list and you can easily access the 4,586th item as easily as you can access the 1st. The list also makes it really easy to apply the same function to every item in the list.

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:

  1. How to create a python list
  2. python list methods:
    1. Accessing items
    2. Adding/Deleting items
    3. Changing an item

Creation Time!

Image for post
Photo by Max LaRochelle on Unsplash

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

Image for post
Photo by Faye Cornish on Unsplash

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:

 birds[0]

OUTPUT:

An example of python lists using indexing

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:

Image for post
index versus negative index
birds[-3]

OUTPUT:

example of python lists using negative indexing

Slicing

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:

birds[0:2]

OUTPUT:

Python lists selecting multiple items

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:

  • +
  • .append(object)
  • .insert(index, object)
  • .extend(iterable)
birds + ['Cardinal']birds.append('Cardinal')birds.insert(4, 'Cardinal')birds.extend(['Cardinal'])

OUTPUT:

multiple ways one can add items to python lists

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”.

Image for post
Photo by Brian McGowan on Unsplash

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:

  • .append()/.insert()

or

  • “+”/.extend()

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'])

OUTPUT:

shows what happens to python lists after python list append
shows what happens to after a python list insert
birds + ['Cardinal', 'Chipping Sparrow']
birds.extend(['Cardinal', 'Chipping Sparrow'])
displays the use of the python lists addition operator
shows what happens with python list extend

Deleting Items from Python Lists

Image for post
Photo by Renee Fisher on Unsplash

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.

anti-house sparrow image
Photo via Good Free Photos

He has several options to remove that wretched House Sparrow from his list:

  • del
  • .remove(object)
  • .pop([i])
  • reassigning item to an empty list
# House Sparrow is located at index 1
del birds[1]

OUTPUT:

displays the use of python lists delete

del is an effective way to delete the item in the list. You can also delete the entire list with this keyword.

birds.remove('House Sparrow')

OUTPUT:

displays python list remove

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

OUTPUT:

shows python list pop

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] = []

OUTPUT:

shows what happens to python list remove

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

Image for post
Both photos via Good Free Photos arrow added by author

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[1] = 'Cardinal'

OUTPUT:

shows what happens with python add to list

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.

2 replies on “Python Lists: A Data Collection Type (Part 1 of 3)”

Comments are closed.