Learn Python – Python List- Basic and advance

A listing in Python is used to store the sequence of a range of types of data. Python lists are mutable type its imply we can modify its thing after it created. However, Python consists of six data-types that are succesful to store the sequences, but the most frequent and dependable kind is the list.

A list can be described as a series of values or objects of extraordinary types. The items in the list are separated with the comma (,) and enclosed with the rectangular brackets [].

A list can be define as below

L1 = ["John", 102, "USA"]    
L2 = [1, 2, 3, 4, 5, 6]   

IIf we attempt to print the kind of L1, L2, and L3 the usage of type() function then it will come out to be a list.

print(type(L1))  
print(type(L2))  

Output:

<class 'list'>
<class 'list'>

Characteristics of Lists

The list has the following characteristics:

The lists are ordered.

The element of the list can access by index.

The lists are the mutable type.

The lists are mutable types.

A list can store the number of various elements.

Let’s check the first announcement that lists are the ordered.

a = [1,2,"Peter",4.50,"Ricky",5,6]  
b = [1,2,5,"Peter",4.50,"Ricky",6]  
a ==b  

Output:

False

Both lists have consisted of the equal elements, however the second list modified the index position of the fifth aspect that violates the order of lists. When compare each lists it returns the false.

Lists maintain the order of the element for the lifetime. That’s why it is the ordered collection of objects.

a = [1, 2,"Peter", 4.50,"Ricky",5, 6]  
b = [1, 2,"Peter", 4.50,"Ricky",5, 6]  
a == b  

Output:

True

Let’s have a look at the list example in detail.

emp = ["John", 102, "USA"]     
Dep1 = ["CS",10]  
Dep2 = ["IT",11]    
HOD_CS = [10,"Mr. Holding"]    
HOD_IT = [11, "Mr. Bewon"]    
print("printing employee data...")    
print("Name : %s, ID: %d, Country: %s"%(emp[0],emp[1],emp[2]))    
print("printing departments...")   
print("Department 1:\nName: %s, ID: %d\nDepartment 2:\nName: %s, ID: %s"%(Dep1[0],Dep2[1],Dep2[0],Dep2[1]))    
print("HOD Details ....")    
print("CS HOD Name: %s, Id: %d"%(HOD_CS[1],HOD_CS[0]))    
print("IT HOD Name: %s, Id: %d"%(HOD_IT[1],HOD_IT[0]))    
print(type(emp),type(Dep1),type(Dep2),type(HOD_CS),type(HOD_IT))  

Output:

printing employee data...
Name : John, ID: 102, Country: USA
printing departments...
Department 1:
Name: CS, ID: 11
Department 2:
Name: IT, ID: 11
HOD Details ....
CS HOD Name: Mr. Holding, Id: 10
IT HOD Name: Mr. Bewon, Id: 11
<class 'list'> <class 'list'> <class 'list'> <class 'list'> <class 'list'>

In the above example, we have created the lists which consist of the worker and department small print and printed the corresponding details. Observe the above code to apprehend the notion of the listing better.

List indexing and splitting

The indexing is processed in the same way as it happens with the strings. The elements of the list can be accessed by means of the use of the slice operator [].

The index starts from 0 and goes to size – 1. The first factor of the list is saved at the 0th index, the 2d aspect of the list is stored at the 1st index, and so on.

We can get the sub-list of the listing the use of the following syntax.

list_varible(start:stop:step)  

The start denotes the starting index position of the list.

The stop denotes the last index position of the list.

The step is used to skip the nth element within a start:stop

Consider the following example:

list = [1,2,3,4,5,6,7]  
print(list[0])  
print(list[1])  
print(list[2])  
print(list[3])  
# Slicing the elements  
print(list[0:6])  
# By default the index value is 0 so its starts from the 0th element and go for index -1.  
print(list[:])  
print(list[2:5])  
print(list[1:6:2])  

Output:

1
2
3
4
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[3, 4, 5]
[2, 4, 6]

Unlike other languages, Python gives the flexibility to use the negative indexing also. The terrible indices are counted from the right. The last component (rightmost) of the listing has the index -1; its adjoining left aspect is current at the index -2 and so on till the left-most elements are encountered.

Let’s have a seem to be at the following example the place we will use negative indexing to get right of entry to the factors of the list.

list = [1,2,3,4,5]  
print(list[-1])  
print(list[-3:])  
print(list[:-1])  
print(list[-3:-1])  

Output:

5
[3, 4, 5]
[1, 2, 3, 4]
[3, 4]

As we discussed above, we can get an aspect by using using negative indexing. In the above code, the first print assertion lower back the rightmost element of the list. The second print assertion back the sub-list, and so on.

Updating List values

Lists are the most versatile facts structures in Python due to the fact that they are mutable, and their values can be updated via the use of the slice and project operator.

Python also presents append() and insert() methods, which can be used to add values to the list.

Consider the following example to update the values internal the list.

list = [1, 2, 3, 4, 5, 6]     
print(list)     
# It will assign value to the value to the second index   
list[2] = 10   
print(list)    
# Adding multiple-element   
list[1:3] = [89, 78]     
print(list)   
# It will add value at the end of the list  
list[-1] = 25  
print(list)  

Output:

[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]

The listing elements can also be deleted by the use of the del keyword. Python also offers us the remove() method if we do no longer be aware of which issue is to be deleted from the list.

Consider the following instance to delete the listing elements.

list = [1, 2, 3, 4, 5, 6]     
print(list)     
# It will assign value to the value to second index   
list[2] = 10   
print(list)    
# Adding multiple element   
list[1:3] = [89, 78]     
print(list)   
# It will add value at the end of the list  
list[-1] = 25  
print(list)  

Output:

[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]

Python List Operations

The concatenation (+) and repetition (*) operators work in the same way as they were working with the strings.

Let’s see how the listing responds to a number operators.

Consider a Lists l1 = [1, 2, 3, 4], and l2 = [5, 6, 7, 8] to perform operation.  
Operator Description Example
Repetition The repetition operator enables the list elements to be repeated multiple times.
L1*2 = [1, 2, 3, 4, 1, 2, 3, 4]
Concatenation It concatenates the list mentioned on either side of the operator.
l1+l2 = [1, 2, 3, 4, 5, 6, 7, 8]
Membership It returns true if a particular item exists in a particular list otherwise false.
print(2 in l1) prints True.
Iteration The for loop is used to iterate over the list elements.
for i in l1: 
    print(i)
Output
1
2
3
4
Length It is used to get the length of the list
len(l1) = 4 

Iterating a List

A listing can be iterated by using the usage of a for – in loop. A easy listing containing four strings, which can be iterated as follows.

list = ["John", "David", "James", "Jonathan"]    
for i in list:   
    # The i variable will iterate over the elements of the List and contains each element in each iteration.     
    print(i)  

Output:

John
David
James
Jonathan

Adding elements to the list

Python provides append() characteristic which is used to add an aspect to the list. However, the append() function can solely add value to the give up of the list.

Consider the following example in which, we are taking the factors of the list from the consumer and printing the listing on the console.

#Declaring the empty list  
l =[]  
#Number of elements will be entered by the user    
n = int(input("Enter the number of elements in the list:"))  
# for loop to take the input  
for i in range(0,n):     
    # The input is taken from the user and added to the list as the item  
    l.append(input("Enter the item:"))     
print("printing the list items..")   
# traversal loop to print the list items    
for i in l:   
    print(i, end = "  ")     

Output:

Enter the number of elements in the list:5
Enter the item:25
Enter the item:46
Enter the item:12
Enter the item:75
Enter the item:42
printing the list items
25  46  12  75  42  

Removing elements from the list

Python affords the remove() characteristic which is used to do away with the factor from the list. Consider the following instance to apprehend this concept.

Example –

list = [0,1,2,3,4]     
print("printing original list: ");    
for i in list:    
    print(i,end=" ")    
list.remove(2)    
print("\nprinting the list after the removal of first element...")    
for i in list:    
    print(i,end=" ")  

Output:

printing original list: 
0 1 2 3 4 
printing the list after the removal of first element...
0 1 3 4 

Python List Built-in functions

Python presents the following built-in functions, which can be used with the lists.

SN Function Description Example
1 cmp(list1, list2) It compares the elements of both the lists. This method is not used in the Python 3 and the above versions.
2 len(list) It is used to calculate the length of the list.
L1 = [1,2,3,4,5,6,7,8]
print(len(L1))
    8
3 max(list) It returns the maximum element of the list.
L1 = [12,34,26,48,72]
print(max(L1))
72
4 min(list) It returns the minimum element of the list.
L1 = [12,34,26,48,72]
print(min(L1))
12
5 list(seq) It converts any sequence to the list.
str = "Johnson"
s = list(str)
print(type(s))
<class list>

Let’s have a look at the few list examples.

Example: 1- Write the software to cast off the duplicate element of the list.

list1 = [1,2,2,3,55,98,65,65,13,29]  
# Declare an empty list that will store unique values  
list2 = []  
for i in list1:  
    if i not in list2:  
        list2.append(i)  
print(list2)  

Output:

[1, 2, 3, 55, 98, 65, 13, 29]

Example:2- Write a application to find the sum of the factor in the list.

list1 = [3,4,5,9,10,12,24]  
sum = 0  
for i in list1:  
    sum = sum+i      
print("The sum is:",sum)  

Output:

The sum is: 67

Example: 3- Write the program to find the lists consist of at least one frequent element.

list1 = [1,2,3,4,5,6]  
list2 = [7,8,9,2,10]  
for x in list1:  
    for y in list2:  
        if x == y:  
            print("The common element is:",x)  

Output:

The common element is: 2