Python Lists: Everything You Need To Know!

In this article, let us learn about Lists in Python and learn how and where to use them in our Python programs.

Lists in a Nutshell

While coding it often makes sense to store a group of items together into a list. In Python, we use the (appropriately named) “list” data structure to do that. Have a look at the following example.

fruit_list = ['apple', 'banana','mango']

As you can see the items are bounded using square brackets, and each item is separated by a comma. The syntax for list declaration is shown below.

list_name = [item1, item2, item3]

If we need to access a specific item on a list, we can do so as follows.

>>> print(fruit_list[0])
apple
>>> print(fruit_list[1])
banana
>>> print(fruit_list[2])
mango

As you can see, the index “0” gives item-1, index “2” gives item-2 and so on. Always remember that in Python (as with many other languages) indexing starts from zero!

In Python, lists are very flexible and you can even put numbers, strings, and letters on the same list like shown below.

mixed_list = [1, 2, 3, 'dog']

Here is a table of useful methods that comes with the List datatype in Python.

SyntaxExampleExplanation
list_name.append(item)mixed_list.append(“cat”) Add a single member, at the end of the list.
mixed_list = [1, 2, 3, “dog”, “cat”]
list_name.insert(index, item)mixed_list.insert(4, 7)Add a single item at the specified index.
mixed_list = [1, 2, 3, ”dog”, 7, “cat”]
list1_name.extend(list2_name)mixed_list.extend([6, 5, 4])Extends mixed_list with a another list “[4, 5, 6]”.
mixed_list = [1, 2, 3, ”dog”, 7, “cat”, 6, 5, 4]
list_name.remove(item)mixed_list.remove(“dog”)Removes the item “dog” from mixed_list
mixed_list = [1, 2, 3, 7, “cat”, 6, 5, 4]
list_name.pop(index)mixed_list.pop(3)Removes mixed_list[3] which is the item “cat
mixed_list = [1, 2, 3, 7, 6, 5, 4]
list_name.sort()mixed_list.sort()Sorts the items of mixed_list in ascending order
mixed_list = [1, 2, 3, 4, 5, 6, 7]
list_name.reverse()mixed_list.reverse()Reverses the order of the items in the list
mixed_list = [7, 6, 5, 4, 3, 2, 1]
list_name.clear()mixed_list.clear()Deletes all items in the list
mixed_list = [ ]

If the above explanation raises more questions than answers, don’t worry as the above answer was only meant to be a quick reference for people who are already familiar with the topic.

If this is your first encounter with “Python Lists” I suggest setting aside 15 minutes of your time and reading through the rest of this article with undivided attention. By the time you reach the end of the article, I assure you that you would have mastered this topic, and you will be equipped with enough knowledge to tackle almost any challenge related to Python lists!

As you read through this article, make sure that you try and run the examples on your computers too, “doing” is the best way of learning!

Tip#1: Feel free to skip the sections marked as “Advanced” on your first read!

We shall start our journey with the creation of lists in Python.

List Creation

Take the example of anything in this world. The thing that is organized attracts attention and looks good. The same applies to the way we organize and manage data inside our code.

In Python, there are 4 main ways in which we can organize and manage collections of data. They are:

  1. List
  2. Tuple
  3. Dictionary and
  4. Set

This article will be all about the 1st item on the above list (Pun intended!)

In our daily lives like we use the word “list” to refer to things like

  • a list of items to be brought from the supermarket or
  • a list of tasks that needs to be done by the end of the day etc.

Lists in Python give us a way to store the information in the above lists inside our code.

For example, let’s say your grocery list looks like the following

  1. Apples
  2. Tomatoes
  3. Shampoo
  4. Cola

You can store these items together in the form of a list in Python as follows.

grocery_list = ["Apples", "Tomatoes", "Shampoo", "Cola"]

I want you to take a closer look at the above line of code.

As you can see

  1. the list is bounded using square brackets, and
  2. each item is separated by a comma.

Just like we use single or double quotes to tell python something is a “string”,we use a pair of square brackets [ ] to tellpython that something is a list.

The syntax for list declaration is shown below.

list_name = [item1, item2, item3]

Tip#2: Nothing irritates a programmer more than googling the syntax while he is trying to code. So I suggest you memorize this syntax!

If you wish to create an empty list and add elements, later on, you can do so in Python as follows

list_name = [ ] # creates an empty list

As you can see using square brackets with nothing inside will create an empty list in Python. But what uses is an empty list? We will show you where to use empty lists and how to add elements to an empty list shortly. For now, just keep in mind the syntax!

Advanced: Another way to create lists

The above syntax is not the only way to create lists, if you are familiar with Object Oriented Programming concepts, you can also the constructor of the list class to do the same.

For example,

>>> fruit_list= list(['apple','mango','banana'])
>>> print(fruit_list)
['apple', 'mango', 'banana']

I am sure you noticed that using empty square brackets to create empty list looks kind of awkward, so if you want to create an empty list in your program, I suggest using the following syntax instead.

>>> empty_list = list()
>>> print(empty_list)
[]

List comprehension is another topic worth looking into if you wish to gain mastery of list creation in Python!

Now that we know how to create a list, next, let us learn how we can make use of the list we just created in our programs.

Accessing individual items

If we need to access a specific item on the list, we can do so as follows.

>>> grocery_list = ['Apple', 'Tomatoes', 'Shampoo', 'Cola']
>>> print(grocery_list[0])
Apple
>>> print(grocery_list[1])
Tomatoes
>>> print(grocery_list[2])
Shampoo
>>> print(grocery_list[3])
Cola

Let’s compare our original list and the one we made in Python,

As you can see,

  • our list started with 1, while in python it starts with index-0. (shown in red) &
  • our list ends with 4, while in python it ends with index-3 (shown in blue)

So python’s count is always 1-less of normal count. You might think that this is a weird way of counting, but it is not just Python, most of the programming languages out there do this the same way and start counting from zero. There is a valid reason behind this, but I will spare you the history lesson! For now, just remember that

Python starts counting from zero instead of one!

Advanced: Another way to access items in the given list

Python also provides us with a cool way of getting the last item in the list.

For example,

>>> list1=['apple', 'mango', 'banana']
>>> print(list1[-1]) # prints the last item of the list 
banana

Hence the index “-1” refers to the last item, “-2” refers to the second last item, and so on.

Slice Notation is another topic worth looking at if you wish to gain mastery in accessing a group of items with a single line of code!

Adding items to the list

Python provides us with the following 3 methods to add items to our lists.

list_name.append(item)Add a single member, at the end of the list.
list_name.insert(index, item)Add a single item at the specified index.
list1_name.extend(list2_name)Extends the given list with another list.

Let us see how and when to use each one with the help of examples.

Append method

Let us start with the simplest of the 3, the append() method.

>>> fruit_list = [ "apple", "mango", "banana"]
>>> fruit_list.append("orange")
>>> print(fruit_list)
['apple', 'mango', 'banana', 'orange']

As you can see our list initially had 3 items: “apple”, “mango”, and “banana”. We added one more item “orange” to the list using the append() method and it got added to the end of the list. That’s how the append() method works!

When you wish to add an item to the end of your list, you can do that using the following syntax

list_name.append(item)

Insert method

Now, what if we wish to insert an item at a specific location? That is where the insert() method comes into play!

>>> odd_number_list = [1, 3, 5, 9]
>>> odd_number_list.insert(3, 7)
>>> print(odd_number_list)
[1, 3, 5, 7, 9]

Here we initially had the list of odd numbers [1, 3, 5, 9], we missed 7 on the list and we have to add it between 5 and 9. If you remember correctly, Python starts counting from zero.

So,

  • 1 is at position-0,
  • 3 is at position-1,
  • 5 is at position-2, and
  • 9 is at position-3.

Now we want to insert 7 at the position where 9 is. To do that we use the following line of code

odd_number_list.insert(3, 7)

This places the item “7” at position-3 and we get the desired list which is [1, 3, 5, 7, 9]. This is how the insert() method works!

When you wish to add an item to the end of your list, you can do that using the following syntax

list_name.insert(index, item)

Extend method

Okay, now we know how to add a single element at a specific location, what if we wish to merge 2 lists?

Consider this example

>>> list1 = [1, 2, 3, 4]
>>> list2 = [5, 6, 7, 8]
>>> list1.extend(list2)
>>> print(list1)
[1, 2, 3, 4, 5, 6, 7, 8]
>>> print(list2)
[5, 6, 7, 8]

Here we just added all the elements of list2 to the end of list1 using the extend() method!

Advanced: Append vs Extend

What will happen if we use the append instead of extend method in the above example?

Let us see what will happen!

>>> list1 = [1, 2, 3, 4]
>>> list2 = [5, 6, 7, 8]
>>> list1.append(list2)
>>> print(list1)
[1, 2, 3, 4, [5, 6, 7, 8]]

Note the extra square brackets before 5 and after 8, what do you think happened here? Take a minute or 2 to think about it and read on!

As we saw at the beginning of the article, list items can be numbers, strings, or any other object in Python. What happened was the list object [5, 6, 7, 8] got added to the end of list1, and hence now list one has four numbers and a list!

We can verify that by seeing what is the item at the 4th index as shown below.

>>> print(list1[4])
[5, 6, 7, 8]

Now that we have learned everything we need to know about adding elements to the list, let us turn our attention to how we can remove elements from our lists!

Removing items from the list

Just like with adding items, Python gives us 3 methods for removing items too.

list_name.remove(item)Removes the 1st occurrence of the item in the list
list_name.pop(index)Removes and returns the item at the specified location
list_name.clear()Removes all the items on the list

Let us see how and when to use each one with the help of examples.

Remove method

Let us start with the simplest of the 3, the remove() method.

>>> list1 = [1, 2, 3, 4]
>>> list1.remove(3)
>>> print(list1)
[1, 2, 4]

As you can see in the code above, remove(3) simply removes the item 3 from the list.

But if you look at the table above, I wrote “Removes the 1st occurrence of the item in the list”, now what did I mean by that? Let’s take another example!

>>> list1 = [1, 2, 3, 4, 5, 4]
>>> list1.remove(4)
>>> print(list1)
[1, 2, 3, 5, 4]

This time as you can see

  • we start with the list with two “4”s in it [1, 2, 3, 4, 5, 4]
  • then when we try to remove the item “4”, the 1st occurrence of 4 is removed (the “4” before “5”).
  • we end up with [1, 2, 3, 5, 4]

So that is how the remove() method works!

But what if we wish to remove the “4” at the end, instead of the “4” in the middle? That is where the pop method comes into the picture!

Pop method

The Pop method removes and returns the item at the specified location. Time for an example!

>>> grocery_list = ['Apple', 'Tomato', 'Shampoo', 'Cola']
>>> grocery_list.pop(1)
'Tomato'
>>> print(grocery_list)
['Apple', 'Shampoo', 'Cola']

As you can see

  • we had a list of 4 items: apple, tomato, shampoo, and cola
  • we “popped” the item on index-1 which is “Tomato”
  • then we have 2 items remaining on the list!

But what did I mean when I said: “removes and returns the item “?

Have a closer look at the example above, especially the 3rd line. Did you notice that it printed out the item we wanted to remove which is ‘Tomato’? That is because the pop method gives it back to the caller!

We can make use of it like follows:

 >>> grocery_list = ['Apple', 'Shampoo', 'Cola']
>>> print("Bought " + grocery_list.pop(0) + ", To buy: " + str(grocery_list))
Bought Apple, To buy: ['Shampoo', 'Cola']
>>> print("Bought " + grocery_list.pop(0) + ", To buy: " + str(grocery_list))
Bought Shampoo, To buy: ['Cola']
>>> print("Bought " + grocery_list.pop(0) + ", To buy: " + str(grocery_list))
Bought Cola, To buy: []

As you can see each time I remove the 1st item (index = 0) and the list gradually goes empty!

So anytime you have a “checklist” type of problem where you need to remove an item from the list that you have just processed, you can use the pop method!

If you wish to pop the last item instead of 1st one, you can simply use “list_name.pop()” without an index. I leave it to you to try it out for yourselves!

Advanced: What does “pop” mean?

The word “pop” comes from the sound made by the cork as you open a bottle like the one in the pic above.

I assume you have played the game of “Jenga”. If you are sliding a block “in”, we call that “pushing” and whenever you take a block “out” we call that “popping”.

But how does that relate to python lists? Similar to the blocks of wood, the items in the list are stored blocks of memory locations. Hence we use the word “pop” to refer to a situation where we take items out of those memory locations!

Another place where the pop method is especially useful is if the remove method is not doing what we want!

>>> list1 = [1, 2, 3, 4, 5, 4]
>>> list1.pop(5)
4
>>> print(list1)
[1, 2, 3, 4, 5]

As you can see above we managed to remove the “4” at the end instead of the “4” in the middle!

To summarize use the pop method whenever you need to

  • process an item from the list and remove it (like a checklist)
  • a list has duplicate items, you just wish to remove one at a specific position.

Enough about the pop method, let us move on to the next one, shall we?

Clear method

The clear method is as simple as it gets, it just deletes all the items in the list leaving an empty list for us to start using again!

>>> grocery_list = ['Apple', 'Tomatoes', 'Shampoo', 'Cola']
>>> grocery_list.clear()
>>> print(grocery_list)
[]

Alright now that we have learned how to add and remove items to/from lists, it is time to move on to the next important concept of how to use lists in a loop!

Looping through a list

Python’s syntax for looping through the items in the list is very easy to read and understand. Consider the example below.

grocery_list = ['Apple', 'Tomato', 'Shampoo', 'Cola']

for item in grocery_list:
        print(item)

Line-3 is where the magic happens. Our list has 4 items and on each loop, the variable “item” gets one of the items of the list (starting from index-0 to the last index) and gives the following output.

Apple
Tomato
Shampoo
Cola

Bear in mind that the variable name “item” was chosen to make the code easy to read, you can change it to any name that suits your purpose. For example, the code below would give the same output as above.

grocery_list = ['Apple', 'Tomato', 'Shampoo', 'Cola']

for i in grocery_list:
        print(i)

See how simple python makes it to loop through a list!

Let us move on to the next section, shall we?

Searching for an item in the list

Now let us see how to search and find items in a list!

The obvious way is to loop through the items, one at a time to figure out whether the item of interest is present in the code or not as shown in the example below.

grocery_list = ['Apple', 'Tomato', 'Shampoo', 'Cola']
item_to_find = 'Shampoo'

for item in grocery_list:
        if item == item_to_find:
              print (item + " found!")

If line-5 above is not clear to you, we have an excellent article explaining the “==” operator for your reference.

Getting back to the topic, searching for an item in a list is one of the use cases which happens all the time while programming. Hence python gives us a shortcut to do the same.

grocery_list = ['Apple', 'Tomato', 'Shampoo', 'Cola']
item_to_find = 'Shampoo'

if item_to_find in grocery_list:
        print(item_to_find + " is found!")

As you can see the code is much shorter and straightforward to understand when we use the “in” keyword in line-4!

If this is your 1st time meeting the “in” keyword, it simply checks if an item is present in a collection or not. To master the concept head over to the article linked here.

Copying Lists

Copying a list is one of the places where C programmers who move to Python struggle the most. If you are one of those people then read this section carefully!

Have a look at the example below.

>>> list1 = [1, 2, 3, 4]
>>> list2 = list1
>>> list2.remove(4)
>>> print(list2)
[1, 2, 3]
>>> print(list1)
[1, 2, 3]

As you can see, we have

  • list1 with 1, 2, 3, and 4
  • then we try to make a new list named “list2” and assign it the contents of list1
  • then we remove the item “4” from list2
  • when list2 is printed we get 1, 2, and 3 as expected (since 4 is removed)
  • but when the list1 is printed we get the same 1, 2, 3

why is that? we explicitly removed the item from list2 in line-3 right?

The reason is because, both list1 and list2 are just 2 names to the same list in memory!

A good analogy here is “synonyms” in the English language, there are several words with the same “meaning”.

Another analogy is a person with 2 names, one “nick-name” and one “official name”, even though the names are different, they both refer to the same person!

In python when we use the “=” operator to relate 2 variables, we are simply creating a new name for the data stored by the 1st variable as shown above

If we wish to make an actual physical copy then we need to make use of the “copy” method

>>> list3 = list1.copy()
>>> list3.remove(3)
>>> print(list3)
[1, 2]
>>> print(list1)
[1, 2, 3]

This will copy the content over to a new memory location as shown below.

As you can see, now when we change list3, list1 stays unaffected!

Sorting Lists

Python provides a method for sorting items in lists using the sort() method. By default, it sorts in ascending order as shown in the example below

>>> fruit_list=[“apple”,”mango”,”banana”,”kiwi”,””pineapple”,”watermelon”]
>>> fruit_list.sort()
>>> print(fruit_list)
[‘apple’,’banana’,’kiwi’,’mango’,’pineapple’,’watermelon’]

If we want to sort in descending order, then we use the reverse method after sorting as shown below

>>> fruit_list=[“apple”,”mango”,”banana”,”kiwi”,””pineapple”,”watermelon”]
>>> fruit_list.sort()
>>> print(fruit_list)
[‘apple’,’banana’,’kiwi’,’mango’,’pineapple’,’watermelon’]
>>> fruit_list.reverse()
>>> print(fruit_list)
[‘watermelon’,’pineapple’,’mango’,’kiwi’,’banana’,’apple’]

You have learned so much about lists, congratulations!

Let us end this article with a quick recap!

Summary

A one-line summary of lists would be

List is a data structure in Python that is mutable, ordered sequences of elements.

Here

  • mutable means we can add or remove elements from it (we cannot in Tuples)
  • ordered means the items are stored in the order in which they came in (not in Sets)

The table below (the same one from the beginning of the article) shows all the useful methods of lists

SyntaxExampleExplanation
list_name.append(item)mixed_list.append(“cat”) Add a single member, at the end of the list.
mixed_list = [1, 2, 3, “dog”, “cat”]
list_name.insert(index, item)mixed_list.insert(4, 7)Add a single item at the specified index.
mixed_list = [1, 2, 3, ”dog”, 7, “cat”]
list1_name.extend(list2_name)mixed_list.extend([6, 5, 4])Extends mixed_list with a another list “[4, 5, 6]”.
mixed_list = [1, 2, 3, ”dog”, 7, “cat”, 6, 5, 4]
list_name.remove(item)mixed_list.remove(“dog”)Removes the item “dog” from mixed_list
mixed_list = [1, 2, 3, 7, “cat”, 6, 5, 4]
list_name.pop(index)mixed_list.pop(3)Removes mixed_list[3] which is the item “cat
mixed_list = [1, 2, 3, 7, 6, 5, 4]
list_name.sort()mixed_list.sort()Sorts the items of mixed_list in ascending order
mixed_list = [1, 2, 3, 4, 5, 6, 7]
list_name.reverse()mixed_list.reverse()Reverses the order of the items in the list
mixed_list = [7, 6, 5, 4, 3, 2, 1]
list_name.clear()mixed_list.clear()Deletes all items in the list
mixed_list = [ ]

Lists are everywhere, even on the computers (or smartphone) that you are reading this article on, you can find lists in

  • the arrangement of your files,
  • your browser’s bookmarks,
  • collections of photos and videos,

and in so many more apps and locations.

Thus, Lists are an incredibly useful datastructure and hats-off to you for mastering it!

Here are some related articles you might find interesting!

Related articles

Python Dictionary: Explained!

Python Sets: Explained!

Credits: Thanks to Sarthak Jaryal for his contributions on creating this article!

Photo of author
Editor
Balaji Gunasekaran
Balaji Gunasekaran is a Senior Software Engineer with a Master of Science degree in Mechatronics and a bachelor’s degree in Electrical and Electronics Engineering. He loves to write about tech and has written more than 300 articles. He has also published the book “Cracking the Embedded Software Engineering Interview”. You can follow him on LinkedIn