In the world of programming, effective data management is a cornerstone of success. Python, a versatile and widely used programming language, provides an array of data structures that empower developers to organize and manipulate data efficiently.
In this blog post, we’ll embark on a journey through Python’s fundamental data structures, exploring how they work and why they are essential for any Python programmer. In this blog series, we will delve deeper into each of these Python data structures, providing practical examples and tips to help you become proficient in their usage.
Python offers a variety of data structures to store and manipulate data efficiently. Stay tuned as we explore Python lists, tuples, sets, and dictionaries in detail, unlocking their full potential to solve real-world programming challenges.
List¶
- List are mutable
- List are slower then tuple.
- List having more functionality as compare to tuple
- Used when we don’t know the exact no of element
- Index start from position 0
- Value enclosed in []
- Collection of different type of element
#List,tuple is type of collection
ls=[1,2,3]
# Reverse of the list element
ls[::-1]
[3, 2, 1]
# list function
ls.append(9)
print(ls)
print(len(ls))
print(ls.index(3))
print(ls.count(3))
[1, 2, 3, 9, 9, 9, 9, 9] 8 2 1
ls[0]='Nitesh' #item re-assignment operation supported by list
print(ls)
['Nitesh', 2, 3]
ls=[1,2,3]
ls.append([4,5])
print(ls)
ls.append('nitesh')
ls.append(['Pandey'])
ls.append(7)
print(ls)
[1, 2, 3, [4, 5]] [1, 2, 3, [4, 5], 'nitesh', ['Pandey'], 7]
ls.clear() #to make list empty
print(ls)
[]
# The copy() of object in other object.
ls=[1,2,3]
num=ls.copy()
print(num)
[1, 2, 3]
num.extend([4]) # changes made to a copy of object do not reflect in the original object
print(num)
print(ls)
[1, 2, 3, 4] [1, 2, 3]
num.count(3) # count the occurrance of element within the list
1
num.index(2) # fetch index position of provided element
1
print(ls)
ls.pop() #By default last element deleted within the list
print(ls)
[1, 2, 3] [1, 2]
ls.remove(1) #Specify the value which need to be remove
print(ls)
[2]
l=[1,2,3,4,9,8]
l.reverse() #reverse the order of list element
print(l)
[8, 9, 4, 3, 2, 1]
del l[2]
print(f'list after deletion of value from index {l}')
list after deletion of value from index [1, 2, 8, 9]
print('Before Sort of list',l)
l.sort() # This function can be used to sort a list in ascending order by default
print('After Sort of list',l)
Before Sort of list [8, 9, 4, 3, 2, 1] After Sort of list [1, 2, 3, 4, 8, 9]
Tuple¶
- Tuple are immutable
- Tuple are faster then list
- Tuple are used as keys in dictionary
- Item can be access through index position
- Represent using ()(Paranthesis)
- Indexing from position 0
- Tuple having less functionality as compare to list
tup=() #empty tuple
print(type(tup))
<class 'tuple'>
tup=(1,2,3)
#tuple is used when we need to restrict from overriding
tup=(1,2,3,'Nitesh')
tup[1] #tuple slicing
2
#Iterate over tuple element
for i in tup:
print(i)
1 2 3 Nitesh
tup.append(6)
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-15-c629cf34c834> in <module>() ----> 1 tup.append(6) AttributeError: 'tuple' object has no attribute 'append'
len(tup)
4
tup[0]='Nitesh' #item re-assignment operation not supported by tuple
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-44-5225ec9592d0> in <cell line: 1>() ----> 1 tup[0]='Nitesh' #item re-assignment operation not supported by tuple TypeError: 'tuple' object does not support item assignment
#Iterate till the length of tuple is exhaust.
for i in tup:
print(tup)
(1, 2, 3, 'Nitesh') (1, 2, 3, 'Nitesh') (1, 2, 3, 'Nitesh') (1, 2, 3, 'Nitesh')
#count and index are only 2 method in tuple
tup.index(3)
tup.count(3)
#concatenation operation performed but append,insert and extend not allowed in tuple
tup1=(1,2,3)
tup2=(4,5,6)
tup1+tup2
(1, 2, 3, 4, 5, 6)
t=tup[::-1]
for t1 in t:
print(t1)
Nitesh 3 2 1
String¶
- String is a sequence of character.
- Strings are a immutable data types which means that its value cannot be updated.
s='NiteshPandey'
print(s[1]) #String Slicing
s[1]='y' #string is immutable
i
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-89-00d6e1c1921e> in <cell line: 4>() 2 print(s[1]) #String Slicing 3 ----> 4 s[1]='y' #string is immutable TypeError: 'str' object does not support item assignment
String Methods¶
Note: All string methods returns new values. They do not change the original string
print(s.capitalize()) #Capitalize first character of string
print(s.count('e')) # Count number of occurance of character/word withing string
Niteshpandey 2
s.endswith('y') #Return Boolean value(True if end with specified character or word else False)
True
# Return -1 if specified character/word not found in string else return the position of where it was found
print(s.find('z'))
print(s.find('N'))
-1 0
print(s.lower()) #Converts a string into lower case
print(s.upper()) #Converts a string into upper case
niteshpandey NITESHPANDEY
s.replace('e','c') #Returns a string where a specified value is replaced with a specified value
'NitcshPandcy'
print(s.title()) #Converts the first character of each word to upper case
print(s.startswith('N')) #Returns true if the string starts with the specified value
print(s.split(' ')) #Splits the string at the specified separator, and returns a list
print(s.strip()) #Returns a trimmed version of the string
Niteshpandey True ['NiteshPandey'] NiteshPandey
Set¶
- remove duplicate values from list or from given element
- case sensitive
- order not maintained
- The data structure used in this is Hashing, a popular technique to perform insertion, deletion and traversal in O(1) on average.
- represent as {}(curley braces)
- used as key in dictionary
- set is mutable
- add,remove allowed but append not
t={}
print(type(t)) #if we want to create empty set then we need to specify the keyword set otherwise it treat dict datatype
s=set()
print(type(s))
<class 'dict'> <class 'set'>
s=set(1,2,3) #always takes value in the form of list
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-57-09c55571445d> in <module>() ----> 1 s=set(1,2,3) #always tkes value in the form of list TypeError: set expected at most 1 arguments, got 3
s=set([1,2,3])
print(s)
print(type(s))
{1, 2, 3} <class 'set'>
s=set([1,2,3,'Nitesh','Pandey',False,True,True,True,True,0,1])
print(s) #it does not return the boolean true for set because 1 occurred before True {True:1,False:0}
{False, 1, 2, 3, 'Pandey', 'Nitesh'}
s=set([1,2,3,'Nitesh','Pandey',0,False,True,True,True,True,0,1])
print(s) # instead of return False it consider False as 0 and return 0
{0, 1, 2, 3, 'Pandey', 'Nitesh'}
s=set(['Nitesh',True,True,False])
print(s)
{False, True, 'Nitesh'}
B = set('hello')
print(B)
A=set('abcdefg')
print(A)
{'l', 'h', 'o', 'e'} {'f', 'e', 'd', 'c', 'b', 'g', 'a'}
[i for i in s]
[False, True, 'Nitesh']
s[0] #slicing is not possible for set because set does not preserved any order
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-29-84f509c3744e> in <cell line: 1>() ----> 1 s[0] #slicing is not possible for set because set does not preserved any order TypeError: 'set' object is not subscriptable
d=set((1,3,6,8,8,'Nitesh','Nitesh',True,True,False)) #set uses list and tuple as parameter
d #very important notes--if we include boolean value in set then instead of returning the value of true or false it doesn`t return because 1 or 0 if already present
{1, 3, 6, 8, False, 'Nitesh'}
e=set((5,3,6,8,8,'Nitesh','Nitesh',True,True,False)) #now it return true values also because set element does not contain any 0 or 1
print(e)
{False, True, 3, 5, 6, 8, 'Nitesh'}
f=set((0,1,6,8,8,'Nitesh','Nitesh',True,True,False)) #now it return true because set element does not contain any 0 or 1
print(f) #now it doesn't return the true and false value because already it's contain 0 and 1
{0, 1, 6, 8, 'Nitesh'}
tup3=(1,2,3,True,False) #tuple not encode the values of true with 1 as set
print(tup3)
(1, 2, 3, True, False)
list=[1,0,True,False] #list not encode the values of true with 1 and 0 with False as set
print(list)
[1, 0, True, False]
s.pop()
False
s.pop()
True
s.pop(1) #specific location element not deleted because set not provide subscript or slicing operation Same has been posible in list
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-25-f06e91dfbaaa> in <module>() ----> 1 s.pop(1) TypeError: pop() takes no arguments (1 given)
n=set([0,9,7,6,8,3,'A',2,4])
print(n)
{0, 2, 3, 'A', 4, 6, 7, 8, 9}
n1=set({1,2,3,8,9,0})
print(n1)
{0, 1, 2, 3, 8, 9}
n2={2,3,4,1,1,0,8,'A','B',222,77,11,22,33,678,678,980}
print(n2)
print(type(n2))
{0, 1, 2, 3, 4, 33, 678, 8, 11, 77, 'A', 980, 22, 'B', 222} <class 'set'>
Dictionary¶
- It is type of data structure in python.
- It define one-to-one relationship between keys and values.
- dictionary are indexed by keys.
- Order not preserved.
- Contain pair of key and their corresponding values.
s={} #when we create empty set then it assume the dict but when we pass one values then it treated as set
type(s)
dict
s={1} #now it act as set instead of dictionary
type(s)
set
#empty dictionary can be created using below method
d=dict()
d
s={} #we can create empty dictionary using this syntax also
type(s)
{}
d=dict({})
d
{}
d={'Name':'Nitesh','Surname':'Pandey'}
print(d)
{'Name': 'Nitesh', 'Surname': 'Pandey'}
d={'Name':'Nitesh','Surname':'Pandey','Name':'Nit'} #overwrite the name value to latest value
print(d)
{'Name': 'Nit', 'Surname': 'Pandey'}
#special character not allowed as key in dictionary
d={'Name':'Nitesh',@:'Nothing'}
File "<ipython-input-49-b8c93957cc61>", line 2 d={'Name':'Nitesh',@:'Nothing'} ^ SyntaxError: invalid syntax
#now special character treated as string hence it allowed
d={'Name':'Nitesh','@':'Nothing'}
print(d)
{'Name': 'Nitesh', '@': 'Nothing'}
d={'Name':['Nitesh','Sarvesh','Nit'],'Age':(19,23,30),'City':set(['Mumbai','Lucknow','Varanasi'])} #tuple,set and list allowed as value in dictionary
print(d)
{'Name': ['Nitesh', 'Sarvesh', 'Nit'], 'Age': (19, 23, 30), 'City': {'Varanasi', 'Mumbai', 'Lucknow'}}
d={'Name':['Nitesh','Sarvesh','Nit'],'Age':(19,23,30),'City':set(['Mumbai','Lucknow','Varanasi','Mumbai'])} #tuple,set,dict and list allowed as value in dictionary
print(d)
{'Name': ['Nitesh', 'Sarvesh', 'Nit'], 'Age': (19, 23, 30), 'City': {'Varanasi', 'Mumbai', 'Lucknow'}}
d={(1,2,3):['Nitesh','Sarvesh','Pandey']} #tuple can also used as key in dictionary because tuple is immutable in nature
type(d)
dict
d[(1,2,3)]
['Nitesh', 'Sarvesh', 'Pandey']
d={(1,2,3):['Nitesh','Pandey']}
print(d[(1,2,3)])
['Nitesh', 'Pandey']
d={(1,2,3):'Nit'}
print(d[(1,2,3)])
Nit
d={(1,2,3):['Nitesh','Pandey'],[1,2,3,4]:'Nit'} #list can not be used as key in dictionary
print(d[(1,2,3)])
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-68-712376195fbf> in <module>() ----> 1 d={(1,2,3):['Nitesh','Pandey'],[1,2,3,4]:'Nit'} 2 print(d[(1,2,3)]) TypeError: unhashable type: 'list'
d={'Dest':'UP',(1,2,3):['Nil',3],'Name':'Nitesh','Age':10}
print(d)
{'Dest': 'UP', (1, 2, 3): ['Nil', 3], 'Name': 'Nitesh', 'Age': 10}
# Keys of dict can be iterate using dict.keys()
for i in d.keys():
print(i)
Dest (1, 2, 3) Name Age
# keys and values can be access using dict.items()
for key,value in d.items():
print(key,':',value)
Name : Nit Surname : Pandey
d.keys,d.values,d.items #inbuilt function
<function dict.keys>
d={}
for i in range(1,10):
d[i]=i**3
print(d)
{1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216, 7: 343, 8: 512, 9: 729}
l=[i**2 for i in range(1,11)] #list comprehension
print(l)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
d={i:i**2 for i in range(1,10)} #dictionary comprehension
print(d)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
These data structures serve different purposes and are used in various scenarios depending on the requirements of your Python program. They are fundamental to data manipulation and organization in Python and play a crucial role in many programming tasks.
“Before we conclude this blog post, we want to extend our sincerest gratitude to you, our valued reader. Your time and attention are precious, and we’re honored that you chose to spend a part of your day with us. We look forward to sharing more with you in the future.”
Thank you !! Happy Learning!!