Introduction to List


☞ It is a data structure.

☞ It is represented by [ ] square brackets.

☞ It is a sequence of python object i.e. integer, float, string, list, boolean, tuple, dictionary etc.

Syntax :
variable_name = [ value1, value2, ………..valueN ]

Creating an empty list

Example :
L1 = []               #empty list
print(L1)

L2 = list()          #empty list
print(L2)
Output
[]
[]

Creating a list with homogeneous and heterogeneous elements

Example :
L3 = [10, 20, 30, 40]              #homogeneous elements
print(L3)

L4 = [10, "inspirewebsoft", 25.6, True, (10,20), [23,14], {"a":5, "b":6}]   #heterogeneous elements
print(L4)
Output
[10, 20, 30, 40]
[10, "inspirewebsoft", 25.6, True, (10,20), [23,14], {"a":5, "b":6}]

Elements are addressed using their index value : The indices of a string begin from 0 to (length-1) in forward direction and -1,-2,-3….,-length in backward direction.

Example :
L4 = [10, 20, 30, 40]

It is mutable, but member objects may be mutable or immutable :

Example 1 :
L = [10, 20, 30, 40]
L[2] = 80 
print(L)
Output
 [10, 20, 80, 40]
Example 2 :
L = [10, 20, ["inspire", "wbe", "soft"], 40]
L[2][1]= "web"       
print(T)
Output
[10, 20, ['inspire', 'web', 'soft'], 40]

Some errors :

Example 1 :
L = [10, 20, 30, 40]    
print(L[5])
Output
print(L[5])
IndexError : list index out of range
Example 2 :
L = [ ]   
L[0] = 10  #cannot assign because list is empty
Output
L[0] = 10 
IndexError: list assignment index out of range