Javatpoint Logo

91-9990449935

 0120-4256464

Python List

1).Python lists are the data structure that is capable of holding different type of data.

2).Python lists are mutable i.e., Python will not create a new list if we modify an element in the list.

3).It is a container that holds other objects in a given order. Different operation like insertion and deletion can be performed on lists.

4).A list can be composed by storing a sequence of different type of values separated by commas.

5).A python list is enclosed between square([]) brackets.

6).The elements are stored in the index basis with starting index as 0.

eg:

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

Accessing Lists

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

Syntax:

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

For accessing list :

<list_name>[index]

Different ways to access list:

Eg:

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:

Data=[1,2,3,4,5];
python string
        Data[0]=1=Data[-5] , Data[1]=2=Data[-4] , Data[2]=3=Data[-3] , 
	Data[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.

List Operations:

Various Operations can be performed on List. Operations performed on List are given as:

a) Adding Lists:

Lists can be added by using the concatenation operator(+) to join two lists.

Eg:

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.

Eg:

 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) Replicating lists:

Replicating means repeating . It can be performed by using '*' operator by a specific number of time.

Eg:

list1=[10,20]
print list1*1

Output:

>>> 
[10, 20]
>>>

c) List slicing:

A subpart of a list can be retrieved on the basis of index. This subpart is known as list slice.

Eg:

list1=[1,2,4,5,7]
print list1[0:2]
print list1[4]
list1[1]=9
print list1

Output:

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

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

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:

a) Updating elements in a List:

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

Syntax:

<list_name>[index]=<value>

Eg:

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]
>>>

b) Appending elements to a List:

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

Syntax:

<list_name>.append(item)

Eg:

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]
>>>

c) Deleting Elements from a List:

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.

Eg:

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]
>>>

Functions and Methods of Lists:

There are many Built-in functions and methods for Lists. They are as follows:

There are following List functions:

FunctionDescription
min(list)Returns the minimum value from the list given.
max(list)Returns the largest value from the given list.
len(list)Returns number of elements in a list.
cmp(list1,list2)Compares the two list.
list(sequence)Takes sequence types and converts them to lists.

1) min(list):

Eg:

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
>>>

2) max(list):

Eg:

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
>>>

3) len(list):

Eg:

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
>>>

4) cmp(list1,list2):

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.

Eg:

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
1
0
>>>

5) list(sequence):

Eg:

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:

MethodsDescription
index(object)Returns the index value of the object.
count(object)It returns the number of times an object is repeated in list.
pop()/pop(index)Returns the last object or the specified indexed object. It removes the popped object.
insert(index,object)Insert 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()Reverse the position of all the elements of a list.
sort()It is used to sort the elements of the List.

1) index(object):

Eg:

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
>>>

2) count(object):

Eg:

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
>>>

3) pop()/pop(int):

Eg:

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]
>>>

4) insert(index,object):

Eg:

data=['abc',123,10.5,'a']
data.insert(2,'hello')
print data

Output:

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

5) extend(sequence):

Eg:

data1=['abc',123,10.5,'a']
data2=['ram',541]
data1.extend(data2)
print data1
print data2

Output:

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

6) remove(object):

Eg:

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]
>>>

7) reverse():

Eg:

list1=[10,20,30,40,50]
list1.reverse()
print list1

Output:

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

8) sort():

Eg:

list1=[10,50,13,'rahul','aakash']
list1.sort()
print list1

Output:

>>> 
[10, 13, 50, 'aakash', 'rahul']
>>>  
Next TopicPython Tuples