List in Python


What is List ?

  • List is an ordered set of values.

  • Values: can be anything, integers, strings, other lists.

  • List values are called elements.

How to create List ?

By using square bracket [ ] , we define a list.

# empty list
my_list = []

# list of integers
my_list = [1, 2, 3]

# list with mixed datatypes
my_list = [1, "Hello", 1.2]

List index :

List elements are index based. It also support positive and negative index as string supports.


my_List = [10,20,"hello",30,40,50,3.2]

<---- +Ve indexes --->
0 1 2 3 4 5 6
10 20 'hello' 30 40 50 3.2
-7 -6 -5 -4 -3 -2 -1
<---- -Ve indexes --->

Access the Element of List :

We can access the element of list using index( +ve or -ve)

Example :

my_List = [10,20,"hello",30,40,50,3.2]
print(my_List[0])
[OUTPUT]
10

print(my_List[2])
[OUTPUT]
'hello' 

print(my_List[-1])
[OUTPUT]
3.2             

print(my_List[7])  remember
[OUTPUT]	    
Traceback (most recent call last):
  File "", line 1, in 
    print(my_List[7])
IndexError: list index out of range

List slicing :

We can slice a list or get a sublist by using slicing operator [ : ].

For more details like syntax refer to String section.

 Revision
list[a:b] means
list[a], list[a+1], …, list[b-1]
# all list elements with indexes from a to b;
# including a and excluding b
--------------------------

my_list = [10,20,30,40,50]
x = my_list[1:4]
print(x)
[OUTPUT]
[20,30,40]

print(my_list[ : ])  similar to my_list[0:len(my_list)]
[OUTPUT]
[10,20,30,40,50]
        
print(my_list[::-1])  reverse
[OUTPUT]
[50, 40, 30, 20, 10]
                

List Operations :

1. Add two lists:
a = [1, 2, 3] b = [4, 5, 6] c = a + b use + operator print(c) [OUTPUT] [1, 2, 3, 4 ,5,6]
2. Repeat a list many times:
a = [1, 2, 3] print(a*3) use * operator [OUTPUT] [1, 2, 3, 1, 2, 3, 1, 2,3]
3. Update list elements:

Since, lists are mutable, we can update the list by using index.

my_list = [10,20,30,40,50] my_list[1] = 100 update index 1 value print(my_list) [OUTPUT] [10, 100, 30, 40, 50] updated
4. List Deletion:

Using the del operator.

names = ['adam', 'carol', 'henry', 'margot', 'phil'] del names[3] delete the value at index 3 print(names) [OUTPUT] ['adam', 'carol', 'henry', 'phil'] Deleting slices names = ['adam', 'carol', 'henry', 'margot', 'phil'] del names[1:4] print(names) [OUTPUT] ['adam', 'phil'] del names[:] removes all elements but not list
5. List Aliasing:

Assign an existing list to a new variable, is called aliasing.

NOTE:

In aliasing, if we make changes into one variable it also reflect into another variable.

a = [1, 2, 3] b = a aliasing b[0] = 0 # update through b print(a) [0, 2, 3] reflected into list a also
6. List Cloning:

Cloning means making an exact but separate copy.

NOTE:

In cloning, if we make changes into one variable it will not reflect into another variable.

a = [1, 2, 3] b = a[:] # cloning print(a) [OUTPUT] [1, 2, 3] print(b) [OUTPUT] [1, 2, 3] # now make change into b b[0] = 10 print(a) [OUTPUT] [1, 2, 3] print(b) [OUTPUT] [10, 2, 3] # We can see, in lis a remain same

List Methods :

MethodDescription
<list>.append(x)Add element x to end of list.
<list>.sortSort (order) the list. A comparison function may be passed as a parameter.
<list>.reverse()Reverse the list.
<list>.index(x)Return index of first occurence of x.
<list>.insert(i,x)Insert x into list at index i.
<list>.count(x)Return the number of occurence of x in list.
<list>.remove(x)Delete the first occurence of x in list.
<list>.pop(i)Deletes the ith element of the list and returns its value.

Adding Elements

List are mutable objects represented by [ ]

List is an ordered collection

my_list = []
print(my_list)

[OUTPUT]
[]
        

append( ) method adds an item at the end of list

my_list.append(9)
my_list.append("hello")
my_list.append(75.2)
print(my_list)

[OUTPUT]
[9, 'hello', 75.2]
 

insert() method adds item at a given index-insert( index,object )

my_list.insert(0,90)
print (my_list)

[OUTPUT]
[90, 9, 'hello', 75.2]
 

We can also insert elements by squeezing the list into an empty slice.

my_list = [1,2,3,4]

# squeez an empty list at index 2

my_list[2:2] = [10,20]
print(my_list)

[OUTPUT]    
[1, 2, 10, 20, 3, 4]
                

extend() method, extend list by appending elements from object

my_list1=[ 78, 23 ]

my_list.extend(my_list1)

print(my_list)

[OUTPUT]
[90, 9, 'hello', 75.2, 78, 23]

my_list.extend("abc")
print(my_list)

[OUTPUT]    
[90, 9, 'hello', 75.2, 78, 23, 'a', 'b', 'c']

my_list.extend([32, "abc", 35.5])
print(my_list)

[OUTPUT]    
[90, 9, 'hello', 75.2, 78, 23, 'a', 'b', 'c', 32, 'abc', 35.5]
 

append() can be used to create nested list

my_list1=[34, 56]
my_list1.append([23, 34])

print(my_list1)

[OUTPUT]    
[34, 56, [23, 34]]
           

count() method is used to count the occurence of an element in list.

my_list=[34,56,38,34,52,56,34]

print(my_list.count(34))

[OUTPUT]    
3
           

sort() method,sort the list in increasing order of elements.

my_list=[34,56,38,34,52,56,34]
my_list.sort()
print(my_list)

[OUTPUT]    
[34, 34, 34, 38, 52, 56, 56]

#sort(reverse=True),sort the list in non increasing
my_list.sort(reverse=True)
print(my_list)

[OUTPUT]    
[56, 56, 52, 38, 34, 34, 34]
           

reverse() method,reverse the list.

my_list=[1,2,3,4,5]
	    
my_list.reverse()
print(my_list)

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

remove() method, searches for an element in list and deletes it.

my_list=[1,2,3,4,5]
	    
my_list.remove(3)
print(my_list)

[OUTPUT]    	    
[1,2,4,5]

my_list.remove(20)  if element is not in list
	    
Traceback (most recent call last):
  File "", line 1, in 
    my_list.remove(20)
ValueError: list.remove(x): x not in list
           

pop() method, by default removes last element, to remove from specific index we can use pop(index) method.

my_list=[1,2,3,4,5]
	    
x = my_list.pop()
print("Popped element =",x)
print("After pop list is\n",my_list)

[OUTPUT]    	    
Popped element = 5
After pop list is
 [1, 2, 3, 4]

x = my_list.pop(0)
print("Popped element =",x)
print("After pop list is\n",my_list)

[OUTPUT]    	    
Popped element = 1
After pop list is
 [2, 3, 4]
           

To find the maximum, minimum,and sum of all elements in list we use the method max() , min() and sum() methods.

my_list=[1,2,3,4,5]
	    
# find the max in list
print("Maximum element =",max(my_list))

[OUTPUT]    	    
Maximum element = 5

# find the min in list
print("Minimum element =",min(my_list))

[OUTPUT]    	    
Minimum element = 1

# find the sum of all element
print("Sum of elements =",sum(my_list))

[OUTPUT]    	    
Sum of elements = 15

           

sorted() method return a sorted list, it won't make changes into actual list.

my_list=[5,4,3,7,8]
x = sorted(my_list)
print(x)

[OUTPUT]
[3, 4, 5, 7, 8]
           

List Iteration :

Using for loop we can iterate each item in a list.

cities = ["Delhi","Mumbai","Kolkata","Chennai","Bangalore"]
>>> for item in cities:
	print(item)

[OUTPUT]	
Delhi
Mumbai
Kolkata
Chennai
Bangalore
     

Nested List :

Nested lists are list objects where the elements in the lists can be lists themselves.

Example :

my_list = [ [1,2,3],
	    [4,5,6],
	    [7,8,9]]
print(my_list)

[OUTPUT]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
                

Access, update, delete the elements in nested list.

my_list = [ [1,2,3],
	    [4,5,6],
	    [7,8,9]]

Abstract representation in row and column

row / col 0 1 2
0 1 2 3
1 4 5 6
2 7 8 9
# Element at 0 index print(my_list[0]) [OUTPUT] [1, 2, 3] # Access 0th index list's 2nd element print(my_list[0][1]) [OUTPUT] 2 # Add new list to existing list my_list.append([10,11,12]) print(my_list) [OUTPUT] [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] # update an element my_list[1][1] = 100 print(my_list) [OUTPUT] [[1, 2, 3], [4, 100, 6], [7, 8, 9], [10, 11, 12]] # delete an element del my_list[1][1] print(my_list) [OUTPUT] [[1, 2, 3], [4, 6], [7, 8, 9], [10, 11, 12]] # Iteration of nested list for i in my_list: print("[",end="") for j in i: print(j,end=", ") print("]") [OUTPUT] [1, 2, 3, ] [4, 6, ] [7, 8, 9, ] [10, 11, 12, ]

Next topic is List Comprehension





 







Training For College Campus

We offers college campus training for all streams like CS, IT, ECE, Mechanical, Civil etc. on different technologies like
C, C++, Data Structure, Core Java, Advance Java, Struts Framework, Hibernate, Python, Android, Big-Data, Ebedded & Robotics etc.

Please mail your requirement at info@prowessapps.in


Projects For Students

Students can contact us for their projects on different technologies Core Java, Advance Java, Android etc.

Students can mail requirement at info@prowessapps.in


CONTACT DETAILS

info@prowessapps.in
(8AM to 10PM):

+91-8527238801 , +91-9451396824

© 2017, prowessapps.in, All rights reserved