Basic Structured Data:
There are a number of collection type available in python that is used to create structured data.
That includes
List
The basic sequence in a structured data in python is a list . A list in python is created using a pair of square bracket around the list of values separated by commas.
.
1 |
a = [1, 2, 3 , 4 ,5 , 6 , 7] |
Example: To print a list
1 2 3 4 5 6 7 8 9 10 |
def main(): name = ['kritika', 'devesh', 'priyam', 'Monica'] print_list(name) def print_list(name): for i in name: print(i) if __name__ == '__main__': main() |
Output:
Find Individual Element in a list:
We can print individual element is a list using index method like print(name[1]).
Example:
1 2 3 4 5 6 |
def main(): name = ['kritika', 'devesh', 'priyam', 'Monica'] print(name[1]) if __name__ == '__main__': main() |
Output :
devesh
Note: The list starts with zero indexes.
Get the range
We can also print the range of items in the list using print(name[1:5:2])
Example: Print every 2nd element starting with 1.
1 2 3 4 5 6 |
def main(): name = ['kritika', 'devesh', 'priyam', 'Monica'] print(name[1:5:2]) if __name__ == '__main__': main() |
Output
[‘devesh’, ‘Monica’];
Appending an item to list:
A list in python is mutable that means we can add or delete item from list once it is created.
Example :
1 2 3 4 5 6 7 |
def main(): name = ['kritika', 'devesh', 'priyam', 'Monica'] name.append('Priyam') print(name) if __name__ == '__main__': main() |
Output
[‘kritika’, ‘devesh’, ‘priyam’, ‘Monica’, ‘Priyam’]
Remove item by value:
We can remove items from the list by using name.remove(‘Monica’)
1 2 3 4 5 6 7 |
def main(): name = ['kritika', 'devesh', 'priyam', 'Monica'] name.remove('Monica') print(name) if __name__ == '__main__': main() |
Output:
[‘kritika’, ‘devesh’, ‘priyam’]
Remove item from end of the list:
You can also remove list item for the end of the list using pop() function
1 2 3 4 5 6 7 |
def main(): name = ['kritika', 'devesh', 'priyam', 'Monica'] x = name.pop() print(x) if __name__ == '__main__': main() |
Output
Monica
Remove item at particular index:
We can also use pop() method to remove item at a particular index
1 2 3 4 5 6 7 |
def main(): name = ['kritika', 'devesh', 'priyam', 'Monica'] name.pop(2) print(name) if __name__ == '__main__': main() |
Output:
[‘kritika’, ‘devesh’, ‘Monica’]
2) Tuple:
Tuple is also a list but it is immutable, that is you can not change the value of tuple once created. It is created with curly brackets
1 |
X = {1, 2, 3,4,5} |
1 2 3 |
X = {1, 2, 3,4,5} X.append(4) print(X) |
Output
Error: AttributeError: ‘set’ object has no attribute ‘append’
3) Dictionaries:
Dictionary in python is a key value pair structure. This is same as associative array in other language like PHP, Javascript
Created using curly braces there is a key value pair, key on left and value on right.
1 2 3 4 5 6 7 |
def main(): info = dict(kritika = "delhi", Devesh = 'Lucknow', Pragya = 'Bhopal', Monica ='Bomaby') for k,v in info.items(): print(k,v) if __name__ =='__main__': main() |
Output:
(‘Monica’, ‘Bomaby’)
(‘Pragya’, ‘Bhopal’)
(‘kritika’, ‘delhi’)
(‘Devesh’, ‘Lucknow’)
We can print the key and values seperatively. Let us look at the example:
To Print Keys:
1 2 3 4 5 6 |
def main(): info = dict(kritika = "delhi", Devesh = 'Lucknow', Pragya = 'Bhopal', Monica ='Bomaby') for k in info.keys(): print(k) if __name__ =='__main__':main() |
Output
Monica
Pragya
kritika
Devesh
To Print values:
1 2 3 4 5 6 |
def main(): info = dict(kritika = "delhi", Devesh = 'Lucknow', Pragya = 'Bhopal', Monica ='Bomaby') for v in info.values(): print(v) if __name__ =='__main__':main() |
Output
Bomaby
Bhopal
delhi
Lucknow
Return The Value from key:
If we want to find what is the value for a particular key we can find it using following example
1 2 3 4 5 |
def main(): info = dict(kritika = "delhi", Devesh = 'Lucknow', Pragya = 'Bhopal', Monica ='Bomaby') print info['Pragya'] if __name__ =='__main__':main() |
Output
Bhopal
Assign different value to a key
We can change the value of the key anytime we want:
1 2 3 4 5 6 7 |
def main(): info = dict(kritika = "delhi", Devesh = 'Lucknow', Pragya = 'Bhopal', Monica ='Bomaby') info['Pragya'] = 'She is from bhopal' for k,v in info.items(): print(k,v) if __name__ =='__main__':main() |
Adding new item to dict
Dict is similar to list and is mutable. We can append new item to the dict
1 2 3 4 5 6 7 |
def main(): info = dict(kritika = "delhi", Devesh = 'Lucknow', Pragya = 'Bhopal', Monica ='Bomaby') info['Divya'] = 'She is new member kerela' for k,v in info.items(): print(k,v) if __name__ =='__main__':main() |
Output:
(‘Monica’, ‘Bomaby’)
(‘Pragya’, ‘Bhopal’)
(‘kritika’, ‘delhi’)
(‘Divya’, ‘She is new member kerela’)
(‘Devesh’, ‘Lucknow’)
Search for item
We can search for an item inside a dict using in operator to return true if the value exists else false.
1 2 3 4 5 |
def main(): info = dict(kritika = "delhi", Devesh = 'Lucknow', Pragya = 'Bhopal', Monica ='Bomaby') print('kritika' in info) if __name__ =='__main__':main() |
Output:
True
Write conditional statement
In python we can use the conditional statement to perform the check this will make the code really short
1 2 3 4 5 |
def main(): info = dict(kritika = "delhi", Devesh = 'Lucknow', Pragya = 'Bhopal', Monica ='Bomaby') print('found ' if 'kritika' in info else 'not found!') if __name__ =='__main__':main() |
Using get method:
If you try to get the key that does not exists it will give you an error. You can use get method
def main():
info = dict(kritika = “delhi”, Devesh = ‘Lucknow’, Pragya = ‘Bhopal’, Monica =’Bomaby’)
print(info.get(‘deepika’))
if __name__ ==’__main__’:main()
You will get none
Python sets:
def main():
a = set(“a set will display random unique value of a srting”)
for x in a:
print x,
if __name__ == ‘__main__’:main()
Op: a e d g f i m l o n q p s r u t w v y
We get unordered list of unique character in a string. Set do not allow duplicates and the list is unordered each time you run the script it will show in differenct order. You can sort the order using sort function.
def main():
a = set(“a set will display random unique value of a srting”)
for x in sorted(a):
print x,
if __name__ == ‘__main__’:main()
Set is like a list that do not allow duplicate elements
List Comprehension:
A list Comprehension is a list created on another list.
Ex Each element in list1 multiplied by two
def main():
seq1 = range(10)
#Print square of this sequence
seq2 = [x*2 for x in seq1]
print_list(seq2)
def print_list(o):
for i in o:
print i,
if __name__ == ‘__main__’:main()
Find all element that are not divided by 3
def main():
seq1 = range(10)
#Print square of this sequence
seq2 = [x for x in seq1 if x%3 != 0]
print_list(seq2)
def print_list(o):
for i in o:
print i,
if __name__ == ‘__main__’:main()
#Creating a list of tuples from the list and its squared element
def main():
seq1 = range(10)
#Creating a list of tuples from the list and its squared element
seq2 = [(x,x**2) for x in seq1]
print_list(seq2)
def print_list(o):
for i in o:
print i,
if __name__ == ‘__main__’:main()
Creating a Dictionary
def main():
seq1 = range(10)
#Creating a list of tuples from the list and its squared element
seq2 = {x:x**2 for x in seq1}
print(seq2)
if __name__ == ‘__main__’:main()