Don't let the Lockdown slow you Down - Enroll Now and Get 3 Course at 24,999/- Only. Explore Now!

General

Python List

Python List

Python List

Python lists are mutable sequences. They are very similar to tuples, but they don’t have the restrictions of immutability. Lists are commonly used to storing collections of homogeneous objects, but there is nothing preventing you from store heterogeneous collections as well. Lists can be created in many different ways.

In this tutorial, you will learn about the lists in Python. A list can be defined as a data structure in which a container is contemplated to be available inside where a large amount of data can be stored at the same time. The list will always contain a sequence where finite numbering will be present. Every element in the list will have a unique space in the numbering order and if in case the same value appears several numbers of times, each value will be decided as a unique element. This tutorial will help you to get a clear idea of ways to create lists in Python and common models possible in the python list.

The utilization purpose of lists will be remarkable if in case you are storing a data sequence to use it for future purposes to serve various tasks.

Let’s see an example:

>>> []  # empty list
[]
>>> list()  # same as []
[]
>>> [1, 2, 3]  
[1, 2, 3]
>>> [x + 5 for x in [2, 3, 4]]  # Python is magic
[7, 8, 9]
>>> list((1, 3, 5, 7, 9))  # list from a tuple
[1, 3, 5, 7, 9]
>>> list('hello')  # list from a string
['h', 'e', 'l', 'l', 'o']

In the previous example, showed you how to create a list using different techniques. would like you to take a good look at the line that says Python is magic, which I am not expecting you to fully understand at this point.That is called a list comprehension, a very powerful functional feature of Python

Creating lists is good, but the real fun comes when we use them, so let’s see the main methods they gift us with:

Example:

>>> a = [1, 2, 1, 3]
>>> a.append(13)  # we can append anything at the end
>>> a
[1, 2, 1, 3, 13]
>>> a.count(1)  # how many `1` are there in the list?
2
>>> a.extend([5, 7])  # extend the list by another (or sequence)
>>> a
[1, 2, 1, 3, 13, 5, 7]
>>> a.index(13)  # position of `13` in the list (0-based indexing)
4
>>> a.insert(0, 17)  # insert `17` at position 0
>>> a
[17, 1, 2, 1, 3, 13, 5, 7]
>>> a.pop()  # pop (remove and return) last element
7
>>> a.pop(3)  # pop element at position 3
1
>>> a
[17, 1, 2, 3, 13, 5]
>>> a.remove(17)  # remove `17` from the list
>>> a
[1, 2, 3, 13, 5]
>>> a.reverse()  # reverse the order of the elements in the list
>>> a
[5, 13, 3, 2, 1]
>>> a.sort()  # sort the list
>>> a
[1, 2, 3, 5, 13]
>>> a.clear()  # remove all elements from the list
>>> a
[]

The preceding code gives you a roundup of a list’s main methods. I want to show you how powerful they are, using extend as an example.

You can extend lists using any sequence type:

>>> a = list('hello')  # makes a list from a string
>>> a
['h', 'e', 'l', 'l', 'o']
>>> a.append(100)  # append 100, heterogeneous type
>>> a
['h', 'e', 'l', 'l', 'o', 100]
>>> a.extend((1, 2, 3))  # extend using tuple
>>> a
['h', 'e', 'l', 'l', 'o', 100, 1, 2, 3]
>>> a.extend('...')  # extend using string
>>> a
['h', 'e', 'l', 'l', 'o', 100, 1, 2, 3, '.', '.', '.']

Now, let’s see what the most common operations are you can do with lists:

>>> a = [1, 3, 5, 7]
>>> min(a)  # minimum value in the list
1
>>> max(a)  # maximum value in the list
7
>>> sum(a)  # sum of all values in the list
16
>>> len(a)  # number of elements in the list
4
>>> b = [6, 7, 8]
>>> a + b  # `+` with list means concatenation
[1, 3, 5, 7, 6, 7, 8]
>>> a * 2  # `*` has also a special meaning
[1, 3, 5, 7, 1, 3, 5, 7]

The last two lines in the preceding code are quite interesting because they introduce us to a concept called operator overloading. In short, it means that operators such as +, -. *, %, and so on, may represent different operations according to the context they are used in. It doesn’t make any sense to sum two lists, right? Therefore, the + sign is used to concatenate them. Hence, the * sign is used to concatenate the list to itself according to the right operand.

How will you create a list?

A list can be created by differentiating the elements using a comma and further need to enclose the list using closed square brackets “[]”. Say for an instance, we can list various technologies and save the sequence of those names as follows:

>>> technologies = [“Python”, “Machine Learning”, “Artificial Intelligence”]
>>> # fetch the name of the first technology
>>> print (technologies[0])
‘Python’
>>> print (technologies[1])
‘Machine Learning’
>>> print (technologies[2])
‘Artificial Intelligence’
>>> if in case, you print the third technology name which is not present in the list >>> it will return an error
>>> print (technologies[3])
Traceback(most recent call last):
File “<stdin>”, line 1, in <module>
IndexError: list index out of range

If we attempt to access an element which is actually not present in the list, it will throw an error as shown above. It is possible to create a two dimensional list. We can apply nesting concept in order to create a two dimensional list.

>>> technologies = [[“Python”, “ML”], [“AWS”, “AI”, “Azure”, “Angular”]]
>>> print (technologies)
[[‘Python’, ‘ML’], [‘AWS’, ‘AI’, ‘Azure’, ‘Angular’]]

The above example is an illustration of two dimensional list where we the elements in the first group and the elements in the second group were grouped together to form a master list.

Methods to work with Python Lists:

Python lists is supported by conventional methods which are usually needed to work with lists. If you need to do make corrections in the list and need to keep both the old list and the recently corrected list, it is possible too. We shall discuss about the same in the following sections.

Adding elements to the list:

We can add new element to the list using the command:

list.append(elem)

This command adds one more element with the list and the same is added in the bottom of the list (end of the list)

Let us see an example of how to add elements to the list:

>>> #initially create an empty list
>>> technologies = []
>>> # now add “Python” to technologies
>>>technologies.append(“Python”)
>>># now add “ML” to technologies
>>>technologies.append(“ML”)
>>># now add “AI” to technologies
>>technologies.append(“AI”)
>>># print items saved in technologies
>>>print(technologies)
[‘Python’, ‘ML’, ‘AI’]

The items were printed as per the sequence in which you have added the elements. The statement, list.insert(index, element) will further insert one more element to the list at the stated index and shifts the elements which are higher than the index to one step from the right. In simpler words, the elements which contain the index larger than the index given will be increased by one. Say for an instance, we shall insert an element in the second position of the list as follows:

>>> technologies = [“Python”, “Machine Learning”, “Artificial Intelligence”]
>>> #print the element present in the second position
>>>print(technologies[2])
Artificial Intelligence
>>>Insert Azure at the second position
>>>technologies.insert(2,”Azure”)
>>>#print the updated list
>>>print(technologies)
[‘Python’, ‘Machine Learning’, ‘Azure’ ‘Artificial Intelligence’]
>>>#print the element in the second position
>>>print(technologies[2])
Azure

It is also possible to add more elements at the end of the list by concatenating them using the statement: list.extend(index_list). This statement will add elements at the end of the list from second position.

>>> location = [“Chennai”, “Bengaluru”, “Pune”]
>>location.extend([“Hyderabad”, “Coimbatore”])
>>>print(location)
[‘Chennai’, ‘Bengaluru’, ‘Pune’, ‘Hyderabad’, ‘Coimbatore’]

We can also add indexes to the list using index method. Similarly, the statement list.index(elem) will provide the index number of those elements present in the list.

Say, for example, we have list of lications with elements such as [‘Chennai’, ‘Bengaluru’, ‘Pune’, ‘Hyderabad’, ‘Coimbatore’] and if you need the index of ‘Hyderabad’, you can go for index method.

We shall write an example for the same.

>>index_of_Hyderabad = location.index(“Hyderabad”)
>>>print(index_of_Hyderabad)
3

Removing elements from the list:

The statement, list.remove(elem) will look for the element which is appearing for the first time and delete it from the list.

Say for an instance, you have a list of locations that contains elements Similarly, the statement list.index(elem) will provide the index number of those elements present in the list.

Say, for example, we have list of locations with elements such as [‘Chennai’, ‘Bengaluru’, ‘Pune’, ‘Hyderabad’, ‘Coimbatore’], you need to delete Hyderabad from the list, you can go for remove method.

>>> locations.remove(“Hyderabad”)
>>> print(locations)
[‘Chennai’, ‘Bengaluru’, ‘Pune’, ‘Coimbatore’]

The statement, list.pop(), will delete the final element present in the list. If the index is given, it will delete the element at the given index. Say for an instance, if the index of the list [,5,3,2,1] and if you apply the ‘pop’ method, the same will return the last element 1 and pop it from the list as follows:

>>> # Consider some numbers and assign them in the list
>>> numbers_assign = [,5,3,2,1]
>>>#perform pop operation
>>> numbers_assign.pop()
1
>>># Print the current list after pop
>>>print (numbers_assign)
[,5,3,2]

We can also remove a random index from the list given. For example,

>>> # perform pop at the element present in index 2
>>> numbers_assign.pop(2)
2
>>># Print the current list after pop
>>>print (numbers_assign)
[,5,3]

Similarly, there are some other list methods were present and one such important list method is sorting. The statement list.sort() will do sorting in the list.

>>> # an unsorted list with some random numbers
>>> numbers_assign = [2,4,3,1]
>>> perform sorting
>>> numbers_assign.sort()
>>> print the current list after sorting
print(numbers_assign)
[1,2,3,4]

It is also possible to reverse the list using the statement list.reverse(). Say for an instance, the list has some numbers [1,2,3,5] and you want to reverse the same, you can go for reverse method in that case.

>>> # a list with some random numbers
>>> numbers_assign = [1,2,3,5]
>>> perform reverse
>>> numbers_assign.reverse()
>>> print the current list after reverse
print(numbers_assign)
[5,3,2,1]

Using Functions in the Python List:

To fetch the length of the list, you can make use of the function “len”

Say, for an instance, you have a list of technologies, [‘Python’, ‘Machine Learning’, ‘Artificial Intelligence’] and you need to predict the length of the list, you can make use of ‘len’ function to get the same.

>>> # the list of technologies
>>>technologies =  [‘Python’, ‘Machine Learning’, ‘Artificial Intelligence’]
>>> predict the length of the list
print(len(technologies))
2

Enumerate is another function that can be used in the python list. It is used to fetch the index as well as the value contained in the element of the list. For an instance, you have the list of technologies, say, [‘Python’, ‘Machine Learning’, ‘Artificial Intelligence’]. Now, you need to know the index, as well as the elements present in the list. In such as case, you can use enumerate function.

>>> # using enumerate function
>>>for indx, name in enumerate (technologies):
....................
Print(“index can be %s for technology:%s: %(indx,name))
....................................
Index is 0 for technology: Python
Index is 1 for technology: Machine Learning
Index is 2 for technology: Artificial Intelligence

In the above example, we have used the ‘for’ loop, which is common in most of the programming languages. With this, we end this tutorial. Hope you had a good understanding. See you all in the next tutorial.

Defining a list in Python

The list elements are enclosed within squared brackets and each element is separated by a comma. Below is an example of a list in Python. Here, the variable named movies_list holds three values which are of string data type.

movies_list = ["Amazing Spiderman", "Harry Potter", "Anaesthesia"]

Accessing a list element in Python

Each value can be accessed individually by referring to the variable name along with the appropriate index number which is enclosed within squared brackets. The index, 0, corresponds to the first element within the array; the index, 1, corresponds to the second value within the list and so forth.

movies_list = ["Amazing Spiderman", "Harry Potter", "Anaesthesia"]
print(movies_list[0])
print(movies_list[1])
print(movies_list[2])

Output

Amazing Spiderman
Harry Potter
Anaesthesia

Adding more elements to a list in Python

You can also add more items or elements of the same data type into the list using the append() method.

movies_list = ["Amazing Spiderman", "Harry Potter", "Anaesthesia"]
movies_list.append("Iron Man")
print(movies_list)

Output

['Amazing Spiderman', 'Harry Potter', 'Anaesthesia', 'Iron Man']        

Removing selected or all elements within a Python list

Likewise, you can also remove an item from a list by using pop() or remove(). By default, pop removes the last item in a list if no index has been referenced. However, you can also choose to remove a specific element by referring to the index corresponding to the item. In this example, index[0] corresponds to “Amazing Spiderman” which would be removed.

Using pop() method

movies_list = ["Amazing Spiderman", "Harry Potter", "Anaesthesia", "Iron Man"]
movies_list.pop(0)
print(movies_list)

Output

 ["Harry Potter", "Anaesthesia", "Iron Man"]

Using remove() method

Similarly, you can use remove() to remove an item from the list. However, instead of referring to an index value, we key in the exact name of the element. It removes only the first occurrence of the value you specified. Also note that it is case sensitive.

movies_list = ["Amazing Spiderman", "Harry Potter", "Anaesthesia", "Iron Man"]
movies_list.remove("Harry Potter")
print(movies_list)

Output

["Amazing Spiderman", "Anaesthesia", "Iron Man"]

Once you remove an item in an array, the order of the index can also change. In the example above, movies_list[1] corresponds to “Harry Potter” before it is removed from the array. After removing it, movie_list[1] would now correspond to “Anaesthesia” as that is the order of the index.

Using clear() method

If you want to remove all the elements in a list, you can use the clear() method.

movies_list = ["Amazing Spiderman", "Harry Potter", "Anaesthesia", "Iron Man"]
print("Before clearing list: ", movies_list)
movies_list.clear()
print("After clearing list: ", movies_list)

Output

Before clearing list:  ['Amazing Spiderman', 'Harry Potter', 'Anaesthesia', 'Iron Man']                             
After clearing list:  []      

Looping through a list in Python

You can also loop through all the items in an array using the for in loop. You can change the “each” keyword to any other word in the example below. Here, “each” represent the individual item within a list and keeps looping through until the last item in the list.

movies_list = ["Amazing Spiderman", "Harry Potter", "Anaesthesia", "Iron Man"]
for each in movies_list:
    print(each)

Output

 Amazing Spiderman
 Harry Potter
 Anaesthesia
 Iron Man

Finding length of list in Python

You can find the length of the list by using the len() method. Length returns the total number of items in a list.

movies_list = ["Amazing Spiderman", "Harry Potter", "Anaesthesia", "Iron Man"]
print("There are ", len(movies_list), "items in this array")

Output

There are 4 items in this array

Sorting lists in Python

The items within a list can be sorted in alphabetical or numerical order by using the sort() method.

movies_list = ["Amazing Spiderman", "Harry Potter", "Anaesthesia", "Iron Man"]
score_list = [3, 6, 3, 1]
print(movies_list.sort())
print(movies_list)
print(score_list.sort())
print(score_list)

Output

['Amazing Spiderman', 'Anaesthesia', 'Harry Potter', 'Iron Man']  
[1, 3, 3, 6]     

Searching a list element in Python

The index() method can be used to find the position or index of an existing element within a list. Enter the name of the element inside the parenthesis to find its index. Note that it is case sensitive.

movies_list = ["Amazing Spiderman", "Harry Potter", "Anaesthesia", "Iron Man"]
print("Index value of Iron Man is ", movies_list.index("Iron Man"))

Output

Index value of Iron Man is  3

Copying a list in Python

A list can be duplicated by using the copy() method where you can copy the list to a new variable.

movies_list = ["Amazing Spiderman", "Harry Potter", "Anaesthesia", "Iron Man"]
movies_list2 = movies_list.copy()
print("Original list: ", movies_list)
print("New list: ", movies_list2)

Output

Original list:  ['Amazing Spiderman', 'Harry Potter', 'Anaesthesia', 'Iron Man']
New list:  ['Amazing Spiderman', 'Harry Potter', 'Anaesthesia', 'Iron Man']    

Click Here-> Get Python Training with Real-time Projects

Besant Technologies WhatsApp