Python List - shahzade baujiti

Breaking

Wednesday, April 24, 2019

Python List

Python List

Python list is a data structure which is used to store various types of data.In Python, lists are mutable i.e., Python will not create a new list if we modify an element of the list.

It works as a container that holds other objects in a given order. We can perform various operations like insertion and deletion on list.A list can be composed by storing a sequence of different type of values separated by commas.

Python list is enclosed between square([]) brackets and elements are stored in the index basis with starting index 0.

Python List Example
data1=[1,2,3,4]; 
data2=['x','y','z']; 
data3=[12.5,11.6]; 
data4=['raman','rahul']; 
data5=[]; 
data6=['abhinav',10,56.4,'a']; 

A list can be created by putting the value inside the square bracket and separated by comma.

Python List Syntax
<list_name>=[value1,value2,value3,...,valuen]; 

Syntax to Access Python List
<list_name>[index] 
Python allows us to access value from the list by various ways.

Python Accessing List Elements Example
data1=[1,2,3,4]; 
data2=['x','y','z']; 
print data1[0] 
print data1[0:2] 
print data2[-3:-1] 
print data1[0:] 
print data2[:2] 

Output:
>>>
>>>
1
[1, 2]
['x', 'y']
[1, 2, 3, 4]
['x', 'y']
>>>

Elements in a Lists:
Following are the pictorial representation of a list. We can see that it allows to access elements from both end (forward and backward).

Data=[1,2,3,4,5]; 



Data[0]=1=Data[-5] ,
Data[1]=2=Data[-4] ,
Data[2]=3=Data[-3] ,  
Date[3]=4=Data[-2] ,
Data[4]=5=Data[-1]. 

Note: Internal Memory Organization:
List do not store the elements directly at the index. In fact a reference is stored at each index which subsequently refers to the object stored somewhere in the memory. This is due to the fact that some objects may be large enough than other objects and hence they are stored at some other memory location.

Python List Operations
Apart from creating and accessing elements from the list, Python allows us to perform various other operations on the list. Some common operations are given below

a) Adding Python Lists
In Python, lists can be added by using the concatenation operator(+) to join two lists.

Add lists Example 1
list1=[10,20] 
    list2=[30,40] 
    list3=list1+list2 
    print list3 

Output:
>>>  
    [10, 20, 30, 40] 
    >>> 

Note: '+'operator implies that both the operands passed must be list else error will be shown.

Add lists Example 2
list1=[10,20] 
list1+30 
print list1 

Output:
Traceback (most recent call last): 
        File "C:/Python27/lis.py", line 2, in <module> 
            list1+30 

b) Python Replicating lists
Replicating means repeating, It can be performed by using '*' operator by a specific number of time.

Python list Replication Example
list1=[10,20] 
print list1*1 

Output:
>>>  
[10, 20] 
>>> 

c)Python List Slicing
A subpart of a list can be retrieved on the basis of index. This subpart is known as list slice. This feature allows us to get sub-list of specified start and end index.

Python List Slicing Example
list1=[1,2,4,5,7] 
print list1[0:2] 
print list1[4] 
list1[1]=9 
print list1 

Output:
>>>  
[1, 2] 

[1, 9, 4, 5, 7] 
>>> 

Note: If the index provided in the list slice is outside the list, then it raises an IndexError exception.

Python List Other Operations
Apart from above operations various other functions can also be performed on List such as Updating, Appending and Deleting elements from a List.

Python Updating List
To update or change the value of particular index of a list, assign the value to that particular index of the List.

Python Updating List Example
data1=[5,10,15,20,25] 
print "Values of list are: " 
print data1 
data1[2]="Multiple of 5" 
print "Values of list are: " 
print data1 

Output:
>>>  
Values of list are:  
[5, 10, 15, 20, 25] 
Values of list are:  
[5, 10, 'Multiple of 5', 20, 25] 
>>> 

Appending Python List
Python provides, append() method which is used to append i.e., add an element at the end of the existing elements.

Python Append List Example

list1=[10,"rahul",'z'] 
print "Elements of List are: " 
print list1 
list1.append(10.45) 
print "List after appending: " 
print list1 

Output:
>>>  
Elements of List are:  
[10, 'rahul', 'z'] 
List after appending:  
[10, 'rahul', 'z', 10.45] 
>>> 

Deleting Elements
In Python, del statement can be used to delete an element from the list. It can also be used to delete all items from startIndex to endIndex.

Python delete List Example
list1=[10,'rahul',50.8,'a',20,30] 
print list1 
del list1[0] 
print list1 
del list1[0:3] 
print list1 

Output:
>>>  
[10, 'rahul', 50.8, 'a', 20, 30] 
['rahul', 50.8, 'a', 20, 30] 
[20, 30] 
>>> 

Python lists Method
Python provides various Built-in functions and methods for Lists that we can apply on the list.

Following are the common list functions.
Function
Description
min(list)
It returns the minimum value from the list given.
max(list)
It returns the largest value from the given list.
len(list)
It returns number of elements in a list.
cmp(list1,list2)
It compares the two list.
list(sequence)
It takes sequence types and converts them to lists.

Python List min() method Example
This method is used to get min value from the list.

list1=[101,981,'abcd','xyz','m'] 
list2=['aman','shekhar',100.45,98.2] 
print "Minimum value in List1: ",min(list1) 
print "Minimum value in List2: ",min(list2) 

Output:
>>>  
Minimum value in List1:  101 
Minimum value in List2:  98.2 
>>> 

Python List max() method Example
This method is used to get max value from the list.

list1=[101,981,'abcd','xyz','m'] 
list2=['aman','shekhar',100.45,98.2] 
print "Maximum value in List : ",max(list1) 
print "Maximum value in List : ",max(list2) 

Output:
>>>  
Maximum value in List :  xyz 
Maximum value in List :  shekhar 
>>> 

Python List len() method Example
This method is used to get length of the the list.
list1=[101,981,'abcd','xyz','m'] 
list2=['aman','shekhar',100.45,98.2] 
print "No. of elements in List1: ",len(list1) 
print "No. of elements in List2: ",len(list2) 

Output:
>>>  
No. of elements in List1 :  5 
No. of elements in List2 :  4 
>>> 

Python List cmp() method Example

Explanation: If elements are of the same type, perform the comparison and return the result. If elements are different types, check whether they are numbers.
If numbers, perform comparison.
If either element is a number, then the other element is returned.
Otherwise, types are sorted alphabetically .
If we reached the end of one of the lists, the longer list is "larger." If both list are same it returns 0.

Python List cmp() method Example

list1=[101,981,'abcd','xyz','m'] 
list2=['aman','shekhar',100.45,98.2] 
list3=[101,981,'abcd','xyz','m'] 
print cmp(list1,list2) 
print cmp(list2,list1) 
print cmp(list3,list1) 

Output:
>>>  
-1 


>>> 

Python List list(sequence) method Example
This method is used to form a list from the given sequence of elements.

seq=(145,"abcd",'a') 
data=list(seq) 
print "List formed is : ",data 

Output:
>>>  
List formed is :  [145, 'abcd', 'a'] 
>>> 

There are following built-in methods of List

Methods
Description
index(object)
It returns the index value of the object.
count(object)
It returns the number of times an object is repeated in list.
pop()/pop(index)
It returns the last object or the specified indexed object. It removes the popped object.
insert(index,object)
It inserts an object at the given index.
extend(sequence)
It adds the sequence to existing list.
remove(object)
It removes the object from the given List.
reverse()
It reverses the position of all the elements of a list.
sort()
It is used to sort the elements of the List.

Python List index() Method Example
data = [786,'abc','a',123.5] 
print "Index of 123.5:", data.index(123.5) 
print "Index of a is", data.index('a') 

Output:
>>>  
Index of 123.5 : 3 
Index of a is 2 
>>> 

Python List count(object) Method Example
data = [786,'abc','a',123.5,786,'rahul','b',786] 
print "Number of times 123.5 occured is",
data.count(123.5) 
print "Number of times 786 occured is",
data.count(786) 

Output:
>>>  
Number of times 123.5 occured is 1 
Number of times 786 occured is 3 
>>> 

Python List pop()/pop(int) Method Example
data = [786,'abc','a',123.5,786] 
print "Last element is", data.pop() 
print "2nd position element:", data.pop(1) 
print data 

Output:
>>>  
Last element is 786 
2nd position element:abc 
[786, 'a', 123.5] 
>>> 

Python List insert(index,object) Method Example
data=['abc',123,10.5,'a'] 
data.insert(2,'hello') 
print data 

Output:
>>>  
['abc', 123, 'hello', 10.5, 'a'] 
>>> 

Python List extend(sequence) Method Example
1.    data1=['abc',123,10.5,'a'] 
2.    data2=['ram',541] 
3.    data1.extend(data2) 
4.    print data1 
5.    print data2 

Output:
>>>  
['abc', 123, 10.5, 'a', 'ram', 541] 
['ram', 541] 
>>> 

Python List remove(object) Method Example
data1=['abc',123,10.5,'a','xyz'] 
data2=['ram',541] 
print data1 
data1.remove('xyz') 
print data1 
print data2 
data2.remove('ram') 
print data2 

Output:
>>>  
['abc', 123, 10.5, 'a', 'xyz'] 
['abc', 123, 10.5, 'a'] 
['ram', 541] 
[541] 
>>> 

Python List reverse() Method Example
list1=[10,20,30,40,50] 
list1.reverse() 
print list1 

Output:
>>>  
[50, 40, 30, 20, 10] 
>>> 

Python List sort() Method Example
1.    list1=[10,50,13,'rahul','aakash'] 
2.    list1.sort() 
3.    print list1 

Output:
>>>  
[10, 13, 50, 'aakash', 'rahul'] 
>>>   

No comments:

Post a Comment