Home Programming Everything about Python Lists

Everything about Python Lists

by Roshan Agarwal
Python Lists

Python has many data types like integer, float, string, list, tuple, etc. In this tutorial, we will learn about the list data type. Lists are one of the most used data types of python and can be used for many operations. 

To follow this tutorial, it is recommended to have the latest python version installed in your system. You can follow our guide on installing the latest version of python. Most of the code in this tutorial can be run in the python shell, but it is recommended to have an IDE to write python code. You can check our comparison on the top 10 IDE for writing code.

Introduction to Python Lists

Python lists are collections of arbitrary objects separated by comma under square brackets like the arrays in C++, javascript, and many other programming languages. But the difference is that the python list can contain different types of data on the same list. 

Example:

>>> list1 = [1, 2, 3, 4]
>>> list2 = ["hello", "this", "is", "a", "list"]
>>> list3 = ["hello", 100, "times"]
>>> list1
[1, 2, 3, 4]
>>> list2
['hello', 'this', 'is', 'a', 'list']
>>> list3
['hello', 100, 'times']

We have created three lists viz. list1, list2, and list3. The list1 contains all its items of the integer data type, the list2 two contains all the string data type items, while the list3 contains both the integer and string data types.

Python Lists are Ordered

Python lists are ordered, which means that we must look at the order while creating lists because two lists with the same elements but different orders will be treated differently by the Python interpreter.

Example:

>>> list1 = [1, 2, 3, 4]
>>> list2 = [4, 3, 2, 1]
>>> list3 = [1, 2, 3, 4]
>>> list1 == list2
False
>>> list1 == list3
True

We can see from the code that list1 and list2, which contains the same elements in different orders, are not equal for python as checked by the ==(equal) operator.

Accessing the items of lists

We can access the items present in a list in many ways.

Indexing

We can use indexing to access an element from a list. In python, indexing starts at 0, so the first element can be accessed by giving the index 0. We can give index in python list by giving the index number in square brackets[ ] at the end of the list variable name. 

Example:

>>> list1 = ["hello", "this", "is", "a", "list"]
>>> list1[0]
'hello'
>>> list1[2]
'is'
>>> list1[4]
'list'

Python indexing starts at 0, so give index as 0 to access the first element, 1 to access the second element.

To access the element by giving the index number of an element that is not present, Python will raise an index error.

>>> list1[5]Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>>

In the code, I have given index number 5 to the list list1, which is out of range as list1 contains only five elements with index number from 0 to 4, so we get an index error.

Negative Indexing

Python also has support for negative indexing. This means that we have a negative number as an index. Using it, we can access the items from last using it. The index -1 means the last element. The index number -2 means the second last element, and so on. 

Example:

>>> list1 = ["hello", "this", "is", "a", "list"]
>>> list1[-1]
'list'
>>> list1[-2]
'a'
>>> list1[-4]
'this'
>>> list1[-5]
'hello'

In the code, it very easy to access the items of the list from the last. This is helpful for long lists in which we don’t know the number of items.

Slicing

Using indexing, we can access only one element simultaneously, but sometimes we need a part of the list or a child list. This can be done using the slicing operator. We need to pass two index numbers in the square bracket separated by a semicolon to do the slicing. The first index number is the first element of the child list, and the second index number is the last element of the child list we want to access. 

Example:

# creating the lists
list1 = [101, 200, 113, 194, 999]
print(list1[0:3])
print(list1[1:])
print(list1[1:4])
print(list1[:])

Output:

slicing of strings

slicing of strings

Changing values of lists

We can easily change a list’s values using indexing, which we learned in the previous topics.

For Eg: Assume that we have created a list with the following data.

>>> year = [2016, 2017, 2018, 2019, 2021]
>>> year
[2016, 2017, 2018, 2019, 2021]

We want to change the year 2021 to 2020; we can do this using the following code. We used indexing and the assignment operator to change the value of the item with index number 4, i.e., the fifth element.

>>> year[4]= 2020
>>> year
[2016, 2017, 2018, 2019, 2020]

From the code, the value changed from 2021 to 2020 of the list variable named year.

Adding Elements on lists

We can add elements to a list in many ways. Some of the popular techniques are discussed below.

Using append() method

The append() function is a built-in function of python, which can add an element at the end of the list. We can also pass a list to a list using the append() function. 

Example:

# created a list fruits
fruits = ["apple", "mango", "banana"]
print(fruits)

# adding kiwi to the fruits
fruits.append("kiwi")
print(fruits)

# adding grapes to the fruits
fruits.append("grapes")
print(fruits)

Output:

append() function

append() function

We can see that the values have been added to the list, but we can only add one item to the list by using this method. To add multiple elements at the end of the list, we need to use the extend function.

Using extend() method

This method is similar to the append() method; the only difference is that we can add multiple elements at once in the list by using this method. 

Example:

# created a list fruits
fruits = ["apple", "mango", "banana"]
print(fruits)

# adding both kiwi and grapes at once to the fruits
fruits.extend(["grapes", "kiwi"])
print(fruits)

Output:

extend() function

extend() function

We can see in the output that both the items have been added to the list simultaneously using the extend() method.

Using insert() method

The above mentioned two functions add the elements at the end of the list. Sometimes we need to add an element at a specific position. This can be done by using the insert() function. It accepts two arguments one is the position, and the other is the value we want to insert.

Example:

# created a list fruits
fruits = ["apple", "mango", "banana"]
print(fruits)

# adding grapes at the third position of the fruits
fruits.insert(2,"grapes")
print(fruits)

# adding grapes at the fifth position of the fruits
fruits.insert(4,"kiwi")
print(fruits)

Output:

insert() function

insert() function

Basic lists operations

We can perform a wide range of operations on the python lists. Some of the basic useful operations are shown below.

Joining lists

There are many ways by using which we can concatenate or join lists together. The easiest way is by using the + operator. 

Example:

# creating the two lists
list1 = ['This', 'is', 'the', 'first', 'list']
list2 = ['This', 'is', 'the', 'second', 'list']
# joining the two lists

list3 = list1 + list2
print(list3)

Output:

merging two string

merging two string

We can also add two lists using the extend() method that we discussed previously. We need to pass the second ist as the argument to extend the () method of the list1 object, and the two lists will be merged. 

Example:

# creating the two lists
list1 = ['This', 'is', 'the', 'first', 'list']
list2 = ['This', 'is', 'the', 'second', 'list']
# joining the two lists using extend() method

list1.extend(list2)
print(list1)

Output:

merging two strings using extend() function

merging two strings using the extend() function

Loop through a lists

The for loop discussed in the tutorial, everything you need to know about for loop can be used to loop through the list. Looping through a list can be useful for accessing the individual data from a list. 

Example:

# creating the lists
list1 = ['This', 'is', 'the', 'first', 'list']
# looping through the list
for item in list1:
print(item)

Output:

iterating a list

iterating a list

Check if an item exists

We can also check if an item exists in a list in python. To do so, we need to use the “in” keyword of python. 

Example:

>>> fruits = ["apple", "mango", "banana"]
>>> "mango" in fruits
True
>>> "kiwi" in fruits
False
>>> "apple" in fruits
True
>>> "banana" not in fruits
False

We use the in keyword to easily identify if an item present on the list or not. We have also use the not keyword with the in keyword to check if an item is not present in the list.

Length of lists

We need to calculate the list’s length to find the number of items contained in the list. We shall see two methods. The easiest method is by using the python’s built-in len() function. 

Example:

# creating the lists
list1 = ['This', 'is', 'the', 'first', 'list']
# calculating the length of the list
length = len(list1)
print("The Length of the list is:",length)

Output:

length of list using len() function

length of list using len() function

We can also use the python for loop to calculate the length of a list. To calculate the length of a list using the for loop, run the following code.

# creating the lists
list1 = ['This', 'is', 'the', 'first', 'list']
length = 0

# calculating the length of the list
for items in list1:
length = length+1

print("The Length of the list is:",length)

Output:

length of list using for loop

length of the list using for loop

Delete List Elements

We can delete an element from a list using two methods, i.e., using the remove() and pop() method.

The pop() method accepts the index number of the item we want to remove from the list. 

Example:

# creating the lists
list1 = ['This', 'is', 'the', 'first', 'list']
# removing the second element from list
list1.remove("is")
print(list1)

Output: We will have “is” removed from the list. 

deleting using remove() function

deleting using remove() function

The remove() functions also work the same way, but we need to give the item an argument to the remove function instead of the index number.

Example:

# creating the lists
list1 = ['This', 'is', 'the', 'first', 'list']
# removing the element by passing the index number
list1.pop(2)
print(list1)

Output: This program will remove the element with index number 2 from the list. 

deleting using pop() function

deleting using pop() function

Built-in methods in lists

There are many built-in methods in python that can be used while manipulating lists. Some of the functions that we discussed include insert(), append(), pop(), remove(), len(), etc. Here are a few more.

clear()

The clear() method of the python list is used to clear the list, i.e., removing every element from the list. 

Example:

>>> list1 = [1, 2, 3, 4] # created the list
>>> list1
[1, 2, 3, 4]
>>> list1.clear() # The list will now become empty
>>> list1
[]

copy()

The copy() method is used to generate a copy of a list. 

Example:

# creating the lists
list1 = ['This', 'is', 'the', 'first', 'list']
list2 = list1.copy()
print(list2)

Output: We have copied the list1 into list2 using the copy() function. 

copy() function of list

copy() function of list

count()

The count() function of the list object is used to count an item’s occurrence in the argument.

Example:

# creating the lists
list1 = ['apple', 'grapes', 'mango', 'apple', 'apple']
# counting the number of occurrence of apple
count = list1.count('apple')

print("The number of occurrence of the item is:", count)

Output: We will get the number of occurrences of the item apple on the list. 

count() method of list

count() method of list

index()

The index() function is used to get the first matched item’s index as the function’s argument.

Example:

# creating the lists
list1 = ['apple', 'grapes', 'mango', 'apple']
# counting the number of occurence of apple
index = list1.index('apple')

print("The first index of the item is:", index)

Output:

index() method of list

index() method of list

reverse()

The reverse() method is used to reverse the order of a list. 

Example:

# creating the lists
list1 = [1, 2, 3, 4]
# reversing the list
list1.reverse()

print(list1)

Output:

reverse() method of lists

reverse() method of lists

sort()

The sort() function is used to sort the items of a list. 

Example:

# creating the lists
list1 = [101, 200, 113, 194, 999]
# sort the list
list1.sort()

print(list1)

Output:

sorting a list

sorting a list

max()

The max() functions will return the maximum of the given list. 

Example:

# creating the lists
list1 = [101, 200, 113, 194, 999]
# the maximum of the list
maximum = max(list1)

print("The first index of the item is:", maximum)

Output:

finding maximum of list

finding the maximum of list

min()

The min() function is similar to the max() function, but instead of returning the maximum value, it will return the minimum.

Conclusion

In this tutorial, we have learned all the necessary concepts of the python lists. You may also like to see the full tutorial on strings in python.

You may also like

Leave a Comment

fl_logo_v3_footer

ENHANCE YOUR LINUX EXPERIENCE.



FOSS Linux is a leading resource for Linux enthusiasts and professionals alike. With a focus on providing the best Linux tutorials, open-source apps, news, and reviews written by team of expert authors. FOSS Linux is the go-to source for all things Linux.

Whether you’re a beginner or an experienced user, FOSS Linux has something for everyone.

Follow Us

Subscribe

©2016-2023 FOSS LINUX

A PART OF VIBRANT LEAF MEDIA COMPANY.

ALL RIGHTS RESERVED.

“Linux” is the registered trademark by Linus Torvalds in the U.S. and other countries.