List
The list is simplest data structure in python which is used to store a collection of data.
The list is a collection of items like String, Numbers, Lists, Tuples, Dictionaries.
Lists are enclosed in square brackets [] .
Each value in the list is assigned to the index value.
An index value of the list is start from 0 .
Each item in list is separated by comma(,) .
List is Mutable data structure which means we can add , remove , replace , append the elements of list whenever we want.
Example : alist = [ 2 , 3 , 4 , 'a' , 7.67 , 'python' ]
How to create List...?
#Creating empty list
#Creating empty list means creating object of list data stucture with no values.
alist = []
print('Initialize empty list : ' , alist )
#Creating a list of strings
alist = ['hii','this','is','Python']
print('List with string values : ' , alist )
#Creating a list of integers
alist = [ 1 ,3, 5 , 7]
print('List with integer values : ' , alist )
#You can also create a list with float , long , complex type integers
#Creating list having mixed type of values(stings , numbers)
alist = [ 345 , 'python' , 6.9836 , 218748682686836753656 , 'program' , 6+8j ]
print('List with mixed type of values : ' , alist )
#Creating list with list type data structure
#List with lst type of items also called as nested lists or multidimensional list.
alist = [[3,4,5],['a','b','c'],[3.67,9,'hello']]
print('Multi-Dimensional List : ' , alist )
#Creating list with the use of tuples
alist = [(4,5,6),('a','v','d'),(3,7,1)]
print('List with the use of tuples : ' , alist )
#Creating list with the use od dictionaries
alist = [{1:'Python' , 2 :'Programming'},{'a' : 97 , 'b' :98 }]
print('List with the use of dictionaries : ' , alist )
Output :
A list may contain duplicate values with their distinct positions .
List store its element according to the index positions so we can store the same element multiple index positions, this can duplicate that element in a list.
If the list contains duplicate elements then that duplicate elements have different index positions.
#Creating a list with duplicate values
alist = [ 'a', 1 ,3 , 3 , 7 ,'a' , 5 , 7]
print('List with duplicate values : ' , alist )
Output :
In above example ,three elements of list have duplicates
element 'a' have two index positions i.e. 0 and 5 .
element 3 have two index positions i.e. 2 and 3 .
element 7 also havetwo index positions i.e. 4 and 7 .
Because of different index positioning these elements considered as distinct elements not as same element .
No comments:
Post a Comment