We can use indexes to access an element in Python lists. Indexing can be of two types positive indexing and negative indexing. Let’s discuss both of index types in detail.
3.1. Positive Indexing in Python
Data in the ith index can be accessed by using listname[i]. Here the listname is the name of the list and i is the index that is to be accessed.
The index number of lists starts from zero and goes up to n-1, where n is the number of elements in the list.
Let’s take some examples to clear the concepts.
list_val=[2, 3, 4, 5, 6]
#updating value at second index
[2, 3, 4, 5, 6]
[2, 3, 4, 9, 6]
In the above example, we can see that the elements of the list list_val=[2,3,4,5,6] have indices 0, 1, 2, 3 and 4 respectively.
Printing list_val would print the whole list whereas printing list_val[i] would print the element in the ith index. The use of lists having integers is pretty much the same as that of using an array in C/C++. But in C++, we can only store items with the same data type. But this is not a problem with the Python list.
The lists in Python are also mutable. This can be seen as list_val was changed from 4 to 9, and the output confirms it without any errors.
We can use lists for different data types as well.
# Holds multiple type of objects in a list
list_item=["str1", 3, "string2", 5, 6, 9.9]
3.2. Negative Indexing in Python
Similar to positive indexing in Python we can also use negative indexes to access the elements of a list. We use negative indexes when we want to access the element from the end.
Let’s go through some examples to to access a list elements using negative indexes.
list_val=[1, 2, 3, 4, 5, 6]
# acess last element
# acess 5th last element
# acess last 3 elements
# acess 4th last to second last element
# acess from first tilll second last element
[4, 5, 6]
[3, 4, 5]
[1, 2, 3, 4, 5]
4. Different Operations on Python Lists
Now, we shall discuss some of the important in-built functions that we can use on a list. We will implement each of them with small examples to understand better.
So let’s get started with one of the most widely used and important operation named Slicing.
Python lists have a special advantage of slicing in which a portion or a section of a list can be simply obtained using the indexes.
Taking a look at the following example:
#This prints elements with indices 0,1,2
#Similarly, upto indices less than 5, i.e. 0,1,2,3,4
#Only index 1
# from second index till the end
[1, 3, 4]
[1, 3, 4, 5, 6]
[4, 5, 6, 8]
From the above example, we can see that
if we print list_val[i:j], the output would be the elements from the index i to index j-1.
for list_val[i:] the output would be from the index i to last element and
for list_val[:j], it will be from the 0th index to index j-1.
4.2. Negative Indexing and Slicing
The indexing can also be done from the last index. If we want to access the elements from the reverse order, we use this method.
Similarly, slicing can also be done by specifying negative indices. This can be cleared out from this example.
#prints 1st element from the reverse direction
# Prints 4th last element
#prints the 4th and 3rd element from the last, i.e. indices 2,3
# Prints last 5 elements
# Both statements are same and print 2,3 and 4th element
From the above example, you can see that if we print a[-i], the output would be the ith element from the end of the list.
Slicing is just the same, but just with negative indices.
We can also mix up negative and positive indices. Only thing we have to remember is that if the number is negative then start counting backwards.
5. How to Delete Elements in Python List?
In Python, we can use del keyboard to delete a single element or the entire list.
Let’s implement an example to delete specific elements from a list and also to delete the entire list.
#deletes element in index 2
#deletes elements with indices 3,4
#deletes last element
#deletes entire list
[1, 3, 5, 6, 8]
[1, 3, 5]
Traceback (most recent call last):
File "", line 1, in
NameError: name 'list_val' is not defined
From the above example we can see that we can not access the list anymore once it is deleted and it throws the error.
6. How to take a list as input in Python?
Now we come to the next question. How to take a list as an input? Suppose we have a sequence of numbers separated by spaces, which we want to store in a list by taking user input. How to achieve this?
Let’s have an overview of the process. As previously stated, Python takes the user input line by line in string format.
So it takes a sequence of numbers that are separated by spaces, then we have to take out the numbers between those spaces and convert them into integers. This process can be done in many ways.
The easiest to understand is –
s = input()
b = map(int, s.split(" "))
a = list(b)
2 4 5 6
[2, 4, 5, 6]
Now let’s just have an explanation of what we did there. There are 3 steps involved here
Line 1 – The user input 2 4 5 6 is stored in a string format, i.e. “2 4 5 6” in a variable ‘s’.
Line 2 – The input string “2 4 5 6” is then split by spaces (If you look at the split() function, the parameter passed is a space character). Then this string format is mapped to integer format using the map() function and is stored in a variable b.
Line 3 – The result b is finally converted into a list and stored in the variable a.
The 3 lines of the previous program can be written in just one line. The program for that would be as folloows.
a = list(map(int, input().split()))
2 4 5 6
[2, 4, 5, 6]
Please go through the explanation once more if there are any doubts.
Note: Here we don’t pass any parameters in the split() function because the default character which it uses to split is the space character. Hence, it is not necessary to pass the space character.
Note: Above examples are only for int but we can do the same for floats, strings, etc, and can use the input() method as per our requirements to initialize the list. We can also use it multiple times to initialize a list of mixed objects.
7. Built-in Functions frequently used for lists
There are some functions that can be applied to a list. Consider a list with name list_name
max(list_name): It returns the maximum value from the given list.
min(list_name): It returns the minimum value from the given list.
len(list_name): It returns the length of the list.
list(list_name): It can be used to assign the whole list to other variables.
sort(): Sorts the list in ascending order.
reverse(): Reverse the order of the list.
append(): Add an element to the end of the list.
extend(): Add all elements of a list to the another list.
insert(): Insert an item at the defined index.
remove(): Removes an item from the list.
pop(): Removes and returns an element at the given index.
clear(): Removes all items from the list.
index(): Returns the index of the first matched item.
count(): Returns the count of the number of items passed as an argument.
Iteration is done by using loops. Here is an example of an array arr, using for loop
arr = list(map(int, input("Enter numbers").split()))
print("Access with index")
for i in range(0, len(arr)):
print("index", i, " - ", arr[i])
print("Access without index")
for item in arr:
2 4 5 6
Access with index
index 0 - 2
index 1 - 4
index 2 - 5
index 3 - 6
Access without index
9. List Membership Test
We can test if an item exists in a list or not, using the keyword in.
list_val = ['c', 'o', 'd', 'i', 'n', 'g', 'e', 'e', 'k']
print('p' in list_val)
print('k' in list_val)
print('c' not in list_val)
In python ,we have some other operations or methods on lists are used to add an element, add another list, remove an element, sort the list, check the existence of an element and other basic functionalities.