In this tutorial, we will master all about python list, the important features of the list, list creation, list manipulation using slicing operator, various list operations, and so on with the help of examples. Also, we will learn about the nested list.
Among the compound datatypes in python, List is the most versatile and commonly used datatype. A list is a sequence-based datatype with a collection of objects. The objects can be of any type.
In python, the List is defined by encasing a sequence of elements in a square bracket [ ]. Each element is separated using commas. The list can embrace any number of elements and can be of any type. The following example would help you to understand how a list is defined in python.
Empty list: A List with no elements or of length 0.
emp_list =[]
Homogenous list: A list with elements of the same datatype.
int_list =[10,20,30]
.
Heterogeneous or Mixed List: A list with elements of different data types
mix_list =['Tom',25,5.9]
Nested List: A List containing another list.
Nest_List = [['Apple', 'Apricot'],['Banana','Blueberry'],"Cherry"]
Like String, items in a list can be accessed either using index []
operator or slicing operator [:]
.We can consider a list as a dynamic array and so indexing and slicing work well with a python list.
Indexing is the process of assigning a number to items in a list for easy access. The index always starts with zero and must be an integer.
Two types of indexing in the python list are :
To understand thoroughly about indexing let’s consider the example and its visualization. ‘LIST’ is a python list consisting of elements ‘RED’, ‘BLUE’,’ GREEN’ & PINK. Each element in the list is assigned with a number corresponding to their position based on positive and negative indexing as shown below.
It is possible to access the individual items from a list by referring to its index number. The below code shows how to access an item using positive indexing.
List = ['Red','Blue','Green','Pink']
print("List[0]=",List[0])
print("List[3]=",List[3])
Output:
List[0]= Red List[3]= Pink
Python list also supports negative indexing to access items from the tail of a list. Negative indexing always starts from the end of the list with index -1.
List = ['Red','Blue','Green','Pink']
print("List[-1]=",List[-1])
print("List[-3]=",List[-3])
Output:
List[-1]= Pink List[-3]= Blue
Python List also works well with range slice operator [:]
.Here, using the slice operator we can slice chunks of items from a list as needed. In short, we can create a sublist using the slice operator. The syntax for Range Slice is
L [ m:n]
where L is the list containing the items
m: starting index
n: ending index
L[m:n] returns the sublist from the index m to n, but excluding the index n.
Slicing itself can be done in various ways with positive and negative indexing. Slicing can be best expressed by placing the items in the middle of indices as illustrated below.
L[m:n]
returns the sublist from position m to n, but excluding index n.
L = ['Red','Blue','Green','Pink','Grey']
print("L[1:3] =",L[1:3])
L[1:3] = ['Blue', 'Green']
L[:n]
returns the sublist from starting position by default to n, but excluding index n.
L = ['Red','Blue','Green','Pink','Grey']
print("L[:2] =",L[:2])
L[:2] = ['Red', 'Blue']
L[m:]
returns the sublist from the position m to the ending index.
L = ['Red','Blue','Green','Pink','Grey']
print("L[2:] =",L[2:])
L[2:] = ['Green', 'Pink', 'Grey']
L[-m:-n]
returns the sublist from position m to n, but excluding index n.
L = ['Red','Blue','Green','Pink','Grey']
print("L[-4:-2] =",L[-4:-2])
L[-4:-2] = ['Blue', 'Green']
L[:n]
returns the sublist from starting position by default to n, but excluding index n
L = ['Red','Blue','Green','Pink','Grey']
print("L[:-2] =",L[:-2])
L[:-2] = ['Red', 'Blue', 'Green']
L[-m: ]
returns the sublist from the position m to the ending index.
L = ['Red','Blue','Green','Pink','Grey']
print("L[-4:] =",L[-4:])
L[-4:] = ['Blue', 'Green', 'Pink', 'Grey']
One of the prominent features that make List a versatile datatype in the python programming language is that “ List are Mutable”. That means a list can be altered after the list has been created. Python List can be modified by adding, removing, or changing items as needed. Python offers a wide variety of ways to alter a list.
Unlike a string, a Python list can be modified by replacing existing items with other items. Indexing makes it easy to replace an item by simply reassigning a new item to the position where we need a change using the assignment operator =. Two possible ways to replace items in a list are:
L = ['Red','Blue','Green','Pink','Grey']
L[0]= 'Yellow'
print('Modified List is :',L)
Modified List is : ['Yellow', 'Blue', 'Green', 'Pink', 'Grey']
L = ['Red','Blue','Green','Pink','Grey']
L[2:4]= ['Orange','Black']
print('List after modificaiton is',L)
List after modificaiton is ['Red', 'Blue', 'Orange', 'Black', 'Grey']
append()
the method is used to add one item to a python list. The syntax is list_name.append(item)
LF =['Daisy','Rose']
LF.append('Tulip')
print("List after appending:",LF)
List after appending: ['Daisy', 'Rose', 'Tulip']
extend()
method is used to add a range of items to a python list. The syntax is list_name.extend([item1, item2,…])
LF =['Daisy', 'Rose', 'Tulip']
LF.extend(['Orchid','Poppy'])
print("Extend List is:",LF)
Extend List is: ['Daisy', 'Rose', 'Tulip', 'Orchid', 'Poppy']
insert()
method is used to insert a particular item at a distinct position in a list. The insert method takes two parameters one for specifying the position and the other for the item. The syntax of insert() is list_name.insert(index, item)
In the below example, item 20 is inserted at position LN[2].
LN =[ 10,30]
LN.insert(2,20)
print(LN)
[10, 30, 20]
del
: To delete a known item from the existing list or to delete the entire list itself. The syntax is del variable_name
L = ['Red','Blue','Green','Pink','Grey']
del L[2];
print(" List after deleting item at index 2 is:",L)
List after deleting item at index 2 is: ['Red', 'Blue', 'Pink', 'Grey']
remove()
method: To remove an item from the existing list. The syntax is List_name.remove(item_name)
.
L = ['Red','Blue','Green','Pink','Grey']
L.remove('Blue')
print("List after removing item : Blue is:",L)
List after removing item Blue is: ['Red', 'Green', 'Pink', 'Grey']
pop()
method: Removes the items at the provided index if the index is given otherwise by default removes and returns the last item. The syntax is List_name.pop(index)
.
L=[10, 20, 30, 40, 50]
L.pop(1);
print("List after removing item at index 1 is :",L)
L.pop();
print("List after removing the last item is:",L)
List after removing item at index 1 is : [10, 30, 40, 50] List after removing the last item is: [10, 30, 40]
So far we have studied the list and its features. Another important feature of a list is its ability to nest. So what do you mean by nesting?
Nesting means storing something inside the other. In python, a nested list is a list containing a list as its element which in turn contains another list.
A nested list is created like how we created the list, the only difference is in the nested list, one or more elements can be a list.
Nest_List = [['Apple', 'Apricot'],['Banana','Blueberry'],"Cherry"]
The nested list can be represented in a hierarchical structure as follows for better understanding.
Accessing items from a nested list is as simple as referring to multiple indexes. We can either access items using positive indexing or negative indexing.
NL = ['a',['bb','cc'],'d',['e',['fff','ggg']],'h','i']
print(NL[3])
print(NL[3][1])
print(NL[3][1][0])
print(NL[4])
Output:
['e', ['fff', 'ggg']] ['fff', 'ggg'] fff h
Let's refer to the pictorial representation of the negative indexing of the nested list.
NL = ['a',['bb','cc'],'d',['e',['fff','ggg']],'h','i']
print(NL[-3])
print(NL[-3][-1])
print(NL[-3][-1][-1])
print(NL[-4])
Output:
['e', ['fff', 'ggg']] ['fff', 'ggg'] ggg d
Similarly, we can modify the nested list by
NL = ['a',['bb','cc'],'d',['e',['fff','ggg']],'h','i']
NL[1][0]= 0
print(NL)
['a', [0, 'cc'], 'd', ['e', ['fff', 'ggg']], 'h', 'i']
NNL = ['a',['bb','cc'],'d',['e',['fff','ggg']],'h','i']
NL[1].append('xx')
NL[1].insert(0,'yy')
NL[3][1].extend([1,2,3])
print(NL)
['a', ['yy', 'bb', 'cc', 'xx'], 'd', ['e', ['fff', 'ggg', 1, 2, 3]], 'h', 'i']
NL = ['a',['bb','cc'],'d',['e',['fff','ggg']],'h','i']
NL[1].pop(0)
print(NL) #removed items bb
del NL[3][1][0]
print(NL) #removed item fff
NL[3][1].remove('ggg')
print(NL)
['a', ['cc'], 'd', ['e', ['fff', 'ggg']], 'h', 'i'] ['a', ['cc'], 'd', ['e', ['ggg']], 'h', 'i'] ['a', ['cc'], 'd', ['e', []], 'h', 'i']
Python list has some built-in functions to perform some usual sequential operations. The basic functions are tabulated below for easy reference.
Function | Description |
---|---|
len(List) | returns the length of the list |
max(List) | returns the largest value among the list |
min(List) | returns the smallest value among the list |
compare(L1,L2) | compares items in list L1 with items in list L2 |
list(seq) | transforms tuple to a list |
As learned in the string, Python List also has operators to do some specific operations. The most common operations are given below for better understanding.
A membership operator is used to validate the presence of an item or a sublist in the list. The corresponding result will a truth value either True or False. Two membership operators in python are:
L =[1,2,3,5,6,8]
print("Validation 3 in List is ",3 in L)
print("Validation 4 not in List is",4 not in L)
Output:
Validation 3 in List is True Validation 4 not in List is True
L1= ['Red','Orange']
L2= ['Blue','Green']
print("Concatenated List is :",L1+L2)
print("Repeated List is:",L1*3)
Output:
Concatenated List is : ['Red', 'Orange', 'Blue', 'Green'] Repeated List is: ['Red', 'Orange', 'Red', 'Orange', 'Red', 'Orange']
We are now familiar with some built-in methods like insert()
,remove()
,pop()
etc. There are few other methods available in the python programming language that works well with list-objects. Methods are accessed using a dot operator like list_name. method_name(parameters)
.
The basic methods are given in a table for easy reference.
Methods | Description |
---|---|
count(p) | Returns the count of occurrence of an item in a list passed as a parameter |
index(p) | Returns the lowest index of the item passed as a parameter |
append(p) | Appends an item passed as a parameter to the list; Add one item to the tail of the list |
extend(list) | Extends the list by adding another list. |
insert(i,p) | Insert a particular item to a specified index where i is the index value and p is the particular item |
remove(p) | Removes an item passed as a parameter from the list |
pop() | By default removes the last item in a list and return the list. |
clear() | Removes all elements from the list |
sort() | By default sorts the list items in ascending order. |
reverse() | Inverse the order of items in a list |
copy() | Returns a shallow or dummy copy of an existing list. |