Common Python List Interview Question and Doubts
Hello! Hope you are doing well? In this article, we will learn and understand Python List. If you don’t know – what is Python programming language? its usage and benefit then I recommend you to go through all about python programming language guide.
Hold tight you will be learning python List today or probably brushing your knowledge on the python list.
Let’s get started!
What is a List in python?
The list is a data structure in python, with a datatype of “list”. The way ArrayList is in Java, Vector in C++ similarly list is in python. The list is a mutable(changeable) ordered sequence of data. List elements/items are ordered, meaning that each element has a defined position and that will not change. The list is mutable, i.e we can perform operations that change, add, remove and update elements/items from the list.
A list can hold DataTypes like integers, strings, and objects. The python list can also hold different data types at the same time. Each data in the list is referred to as elements or items which are indexed. List index count starts from 0. Python list also allows duplicate elements, since each element will be having its own index position and credibility. Lists are created using squared brackets [] or list() python constructor.
Do remember, that other data types can also be converted to a list using python type conversion.
#!/usr/local/bin/python3 #command to run the file: python3 ./creating_list.py # Python code example of Creating a List. demo_list0 = [] print("Empty List: ", demo_list0) # Creating a List holding numbers. demo_list1 = [5, 8, 17, 2] print("\nList of numbers: ", demo_list1) # Creating a List containing strings. demo_list2 = ["Goa", "Panjab", "Kolkata"] print("\nList Items: ", demo_list2) # Creating a List of different data types. demo_list3 = ["Goa", 9, 3.6] print("\nList Items: ", demo_list3) # Creating a Multi-Dimensional List. demo_list4 = [['Goa', 'Delhi'] , ['Kolkata']] print("\nMulti-Dimensional List: ",demo_list4)
How to get the length or number of elements of a python list?
One can determine the length of a list or the number of items in a list by using len() function.
#!/usr/local/bin/python3 #command to run the file: python3 ./list_length.py # Python code example of Creating a List. demo_list0 = [] print("Empty List length: ", len(demo_list0)) # Creating a List of different datatypes demo_list1 = ["Goa", 9, 3.6] print("\nList Items length: ", len(demo_list1)) # Creating a Multi-Dimensional List demo_list2 = [['Goa', 'Delhi'] , ['Kolkata']] print("\nMulti-Dimensional List length: ",len(demo_list2))
How to access python list items?
As we mentioned above list items are indexed i.e each element of the list has a unique index number. Using this index number a specific item from the list can be retrieved. This method is also known as positive indexing i.e accessing the list from the beginning of the list.
Say there is a python list named demoList = [“GA”, “MH”, “PB”, “DL”, “OD”, ”UP”]. For example, demoList[2] will give a list element at index number 2, which will be the third element from the start of the list i.e “PB”.
A list can also be accessed using negative indexing. Negatives here indicate that a list will be accessed from the end.
Say I use the above example and change 2 to -2 i.e demoList[-2]. This will give us elements at index 2 from the end of the list. Which will be the third last element of the list i.e “DL”.
So far we learned to access an element from a list. Now we will learn how to access a range of elements from a list using a range of indexes. To get a range of values one can set start to one index number and end to another index number. For example, demoList[1:3], will return a new list with values falling within the specified index number range. So here we will be getting [“MH”, ”PB”]. This is also known as positive range indexing.
In range indexing access methods, if you miss out start index then you will get range from the start of the list till the specified end index number. If you miss out on the end index then you will get a range from the start index number till the end of the list.
For example, demoList[:3] will return a list equal to [“GA”, “MH”, “PB”].
Similarly for example demoList[3:] will return a list equal to [“DL”, “OD”, ”UP”].
Same as above we have negative range indexing. Like negative indexes which return elements from the end of the list, negative range indexing returns a range of values from the end of the list.
For example, demoList[-3:-1] will return a list containing [“DL”, “OD”].
NOTE:
- In range indexing, say syntax is [startIndex, endIndex]. The resultant list will include the value of startIndex but exclude value of endIndex.
- A list is always numbered 0 to N, from beginning to end while accessing. So in case of positive indexing it will start from 0. Whereas in negative indexing the search for index starts from the end of list from 1 to N. for example index number for demoList in positive index will be [0, 1, 2, 3, 4, 5] and negative index will look like this [-6, -5, -4, -3, -2, -1]
#!/usr/local/bin/python3 #command to run the file: python3 ./access_list.py # Python code example of Creating a List. demo_list = ["GA", "MH", "PB", "DL", "OD", "UP"] print("List is : ", demo_list) # Access list item using index number (Positive Indexing) print("Positive indexing : ",demo_list[2]) # Access list item using negative index number (Negative Indexing) print("Negative indexing : ",demo_list[-2]) #Positive range indexing print("Positive range indexing : ",demo_list[1:3]) #Negative range indexing print("Negative range indexing : ",demo_list[-3:-1])
How to check if an item or value is present in a python list?
This can be achieved using if condition and in operator. For example check if Goa is present in state_list=[“Goa”, “Panjab”, “Delhi”, “Odisha”].
#!/usr/local/bin/python3 #command to run the file: python3 ./ckeck_list_item.py # Creating a state list. state_list = ["Goa", "Panjab", "Delhi", "Odisha"] print("List is : ", state_list) if "Goa" in state_list: print("Yes, Goa is in given state list")
How to change python list items?
List indexes are not only used to access list items but also used for a lot more operations on lists.
To change a specific list item we use an index. Using an index will change the value of the item present in the index.
For example, consider demo_list=[“GA”, “MH”, “PB”, “DL”, “OD”, ”UP”] and we want to change the item at index 2. This can be done like this demo_list[2] = “KA”.
Same like accessing the range of list elements one can change the range of list elements using positive range indexing. To do so first you need to create a list with new items and then point it to the range of index where you want to insert this new value.
For example, demo_list[1:3] = [“UP”,” KR”], this will replace “MH”, “PB” items, and the demo_list = [“GA”, “UP”,” KR”, “DL”, “OD”, ”UP”]
Say, if the number of new items is more than the specified range to be replaced. In such a scenario, the additional value will be added after the end index (specified in the range) and the existing value will shift accordingly.
For example: demo_list[1:3] = [“AP”,”CT”, “DD”] the demo_list will look like this demo_list = [“GA”, “AP”,”CT”, “DD”, “DL”, “OD”, ”UP”].
Note: in range indexing, the end index is not considered, the operation stops always at ends index-1.
But say you added less number of new items than the specified range for a replacement. In this case, the new values will be stored in the place of the specified range and other existing values will adjust accordingly.
For example: demo_list[1:4] = [“UP”,”KR”] the above demo_list will look like this demo_list = [“GA”, “UP”,”KR”, “DL”, “OD”, ”UP”]. You will notice that “CT” and “DD” got replaced with “KR”.
#!/usr/local/bin/python3 #command to run the file: python3 ./change_list_item.py # Creating a state short code list. state_code_list = ["GA", "MH", "PB", "DL", "OD", "UP"] print("State code list is : ", state_code_list) #change list item using index state_code_list[2] = "KA" print("list is : ", state_code_list) #change list item using index range state_code_list[1:3] = ["UP","KR"] print("list is : ", state_code_list) #change list item using index range where replacing value is more then the range specified. state_code_list[1:3] = ["AP","CT", "DD"] print("list is : ", state_code_list) #change list item using index range where replacing value is less then the range specified. state_code_list[1:4] = ["UP","KR"] print("list is : ", state_code_list) #change list item by inserting new value at specified position. state_code_list.insert(4,"HR") print("after insert list is : ", state_code_list)
How to add elements or items to a python list?
Items or elements can be added to a list by inserting values to a list, appending items to a list, or extending the list. Let’s go through each of these methods in detail.
Adding item to list using insert() method.
In python list insert() method allows us to add items to the list without replacing any existing items on the list. Moreover, it also gives us control over the position of the insert for new items, by specifying index numbers.
Syntax is listName.insert(index number, new value)
For example: Insert new value “HR” at index 3 of demo_list where demo_list= [“GA”, “UP”,” KR”, “DL”, “OD”, ”UP”]. As pseudocode, it will be something like this demo_list.insert(4, “HR”) result of which will be demo_list=[“GA”, “UP”,” KR”, “DL”,” HR”, “OD”, ”UP”].
Adding item to list using append() method.
Python has an inbuilt method append() that can be used to append value to a list. Appending as the name suggests will add value at the end of the list and does not allow us to control the position of the new item.
Syntax is listName.append(new value).
For example: Append the new value “AP” to the demo list [“GA”, “UP”,” KR”, ”PO”]. That can be done by demo_list.append(“AP”), the result of which will be demo_list=[“GA”, “UP”,” KR”, ”PO”, “AP”].
Adding multiple items to a list using extend() method.
The Python Extend method allows us to add multiple items (stored in a list) to a list (existing list). All the new items will be added at the end of the main list or say the current list.
Syntax is CurrentListName.extend(AnotherListName).
For example: add list1=[“MP”,” AN”] to the demo list [“GA”, ”UP”]. I.e. demo_list.extend(list1) result of which will be demo_list=[“GA”, “UP”, ”MP”, “AN”].
Adding set, dictionary, and tuples to a list using extend() method
Extend is also used to add items from other data structures like sets, tuples, dictionaries, etc.
For example set1=(“RJ”, “LD”) and say the demo_list=[“MH”, “DL”, “GJ”]. the extend method i.e demo_list.extend(set1) will give me demo_list=[“MH”, “DL”, “GJ”,” RJ”, “LD”]
#!/usr/local/bin/python3 #command to run the file: python3 ./add_list_item.py # Creating a state short code list. state_code_list = ["GA", "UP", "KR", "DL", "OD", "UP"] print("State code list is : ", state_code_list) #Adding item to list using insert() method. state_code_list.insert(3,"HR") print("after insert list is : ", state_code_list) #Adding item to list using append() method. state_code_list.append("AP") print("after append list is : ", state_code_list) #Adding multiple items to a list using extend() method. list1=["MP","AN"] state_code_list.extend(list1) print("after extend list is : ", state_code_list) #Adding set to a list using extend() method. set1=("RJ", "LD") state_code_list.extend(list1) print("after adding set the list is : ", state_code_list)
How to remove elements or items from a python list?
In a python list, we can use the list method to remove items from a list. The methods that can be used for this operation are removed(), pop(), and clear(). Apart from the python list method, we can also use the del statement to delete an item or elements from a python list.
Let’s cover each of these techniques below.
Remove specific items or elements from the list.
Python provides an inbuilt remove() method, this method removes the specified elements from the python list.
For example: say the demo_list=[“GA”, “UP”, ”KR”, ”PO”] and I run the operation demo_list.remove(“KR”). The demo_list will now have [“GA”, “UP”, ”KR”, ”PO”].
Remove items or elements from the python list by index number.
Pop is also a python method that removes elements from a list present on a specified index. Otherwise pop() without a specified index removes the last elements from the list.
For example: say the demo_list=[“GA”, “UP”, ”KR”, ”PO”], and I run the operation demo_list.pop(1). The demo_list will now have [“GA”, ”KR”, ”PO”].
Next, say I run demo_list.pop(), now the demo list will have [“GA”, ”KR”].
Remove all items from a python list i.e empty out a python list using the clear method.
The clear() python list method empties the list. In other words, it removes all elements from a list, leaving the list without any content. The list still remains though.
For example: say the demo_list=[“GA”, “UP”, ”KR”, ”PO”], and I run the operation demo_list.clear(). The demo_list will now have [].
Remove specific index corresponding elements from the python list.
Same as the pop method we can use the del keyword to remove elements from the list using an index number. In addition to this, del can also completely del a list.
For example: say the demo_list=[“GA”, “UP”, ”KR”, ”PO”,” AP”] and I run the operation del demo_list[3]. The demo_list will now have [“GA”, “UP”, ”KR”, ”AP”].
If run del demo_list the demo list is completely deleted.
#!/usr/local/bin/python3 #command to run the file: python3 ./remove_list_item.py # Creating a state short code list. state_code_list = ["GA", "UP", "KR", "OD", "UP"] print("State code list is : ", state_code_list) #Remove item from list using remove() method. state_code_list.remove("KR") print("after remove list is : ", state_code_list) #Remove item from list using pop() method. state_code_list.pop(2) print("after pop(2) list is : ", state_code_list) state_code_list.pop() print("after pop() list is : ", state_code_list) #Remove item from list using clear() method. state_code_list.clear() print("after clear list is : ", state_code_list) state_code_list = ["GA", "UP", "KR", "OD", "UP"] #Remove item from list using clear() method. del state_code_list[3] print("after del index 3 list is : ", state_code_list) del state_code_list print("after del list is : ", state_code_list) # will throw an error since list is deleted.
Hope I have made it easy to understand the python list and its basic operations.
If you have any questions or comments feel free to reach me at.
Checkout out other python concept covered in Python Tutorial