The world’s leading publication for data science, AI, and ML professionals.

5 Questions to Consolidate Your Knowledge of Python Lists

Picked from Stackoverflow

Photo by Zan on Unsplash
Photo by Zan on Unsplash

Python has 4 built-in data structures: List, Tuple, Set, and Dictionary. These data structures are extremely important even if you are using Python for Data Science.

All of them are essentially a collection of data. However, there are differences among them which make each data structure unique. For instance, lists are mutable whereas tuples are immutable. We cannot append a new item to a tuple.

In this article, we will go over 5 questions that demonstrate a particular feature of Python lists. I have picked questions that have a high number of votes on Stackoverflow so we can assume they are frequently asked by the Python community.

A Python list is an ordered sequence of elements which are written in square brackets and separated by commas. The following is a list of 4 elements.

mylist = [4, True, "a", 15]

As we can see in this example, lists can store objects with different data types.


1. How do you check if a list is empty?

There are multiple ways of checking if a list is empty. For instance, we can find the length of a list with the len function and if it is 0 then the list is empty.

mylist = []
if len(mylist) == 0:
    print("The list is empty!")
# output
The list is empty!

A more pythonic way of doing this is based on the fact that empty sequences are false.

mylist = []
if not mylist:
    print("The list is empty!")
# output
The list is empty!

2. What is the difference between the append and extend methods?

The append method is used for adding a new item (e.g. appending) to a list whereas the extend method adds items in another collection to a list. In other words, the extend method extends a list by using the items in the given collection.

Let’s go over a few examples to demonstrate how they are used.

a = [1, 2, 3]
a.append(4)
print(a)
# output
[1, 2, 3, 4]

If you pass a collection to the append method, it will be added as a single element to the list.

a = [1, 2, 3]
a.append([4, 5])
print(a)
# output
[1, 2, 3, [4, 5]]

The list "a" has 4 items. If we do the same example using the extend method, the resulting list will have 5 items because 4 and 5 will be added as separate items.

a = [1, 2, 3]
a.extend([4, 5])
print(a)
# output
[1, 2, 3, 4, 5]

3. How do you get the last item in a list?

There is a very simple way of getting the last item in a list. The index of the first item of a list is 0. The index of the last item, of course, depends on the length of the list. However, we have the option to start the index from the last item. In this case, the index starts from -1.

a = [1, 2, 3, 4]
a[-1]
# output
4

There is an exception to this method which is the case of an empty list. If the list is empty, the above method generates an index error. We can solve this problem with a simple as below:

a = []
a[-1:]
# output
[]

The output is still an empty list but the code does not throw an error.


4. How do you flatten a list?

Consider we have a list of lists as below:

a = [[1, 2], [3, 4], ["a", "b"]]

We want to flatten it which means converting it to a list of items as below:

a = [1, 2, 3, 4, "a", "b"]

Again, there are multiple ways of performing this task. We will be using a list comprehension.

a = [[1, 2], [3, 4], ["a", "b"]]
b = [item for sublist in a for item in sublist]
print(b)
# output
[1, 2, 3, 4, 'a', 'b']

If the syntax of a list comprehension seems confusing, try to think of it as nested for loops. For instance, what the list comprehension above does can be accomplished with the following nested for loops:

b = []
for sublist in a:
    for item in sublist:
        b.append(item)

print(b)
# output
[1, 2, 3, 4, 'a', 'b']

5. How do you remove duplicates in a list?

Again, there is more than one way to do this task. The simplest one might be using the set constructor. Set is another built-in data structure in Python. One of the identifying features of sets is that they do not contain duplicates.

a = [1, 1, 2, 3, 3, 4, 5, 6, 7, 7, 7]
b = list(set(a))
print(b)
# output
[1, 2, 3, 4, 5, 6, 7]

We first convert the list to a set and then convert it back to a list.


Lists are frequently used in Python. They are versatile and highly practical which make them the preferred data structure in many cases.


You can become a Medium member to unlock full access to my writing, plus the rest of Medium. If you already are, don’t forget to subscribe if you’d like to get an email whenever I publish a new article.

Join Medium with my referral link – Soner Yıldırım

Thank you for reading. Please let me know if you have any feedback.


Related Articles