DAY 4 - Data Types
#PythonDataTypes
#list [] tuple () dictionary {key:value} set {}
#immutable objects - Number values, strings and tuple
#mutable objects - list and dictionary
These are built-in data types in Python:
1. Numeric
a. Integer - # type(7) <class 'int'>
b. Float - a real number with a fractional component #type(7.0) <class 'float'>
c. Complex Number - a + bj where a and b are floats and j is -1(square root of -1 called an imaginary number) #type(5+6j) <class 'complex'>
Conversion:
> int(7.5) 7
> float(7) 7.0
> complex(7.5) (7.5+0j)
> float(5+6j) TypeError: can't convert complex to float
Operations:
+ (Addition),- (Subtraction),* (Multiplication),/ (Division),% (Modulus),** (Exponent),// (Floor Division)
Built-In Functions:
int,float,complex,hex,oct,pow,abs,round.
2. Boolean
This datatype is mainly used in IF-ELSE statement. for example: 5 > 4 True
Conversion:
bool(7) True bool(5+4j) True bool('rakesh') True bool([]) False
bool(['rakesh']) True bool({}) False bool(('rakesh')) True and so on
3. Sequence Type: A sequence is an ordered collection of similar or different data types.Its element can be fetched using indices.
a. String : It's a collect of character(s) enclosed within a single,double or triple quotes. for example: 'Rakesh'
Operations:
+,*,Slicing Operator: []/[:],in,not in
Built-In Functions:
String.capitalize(),String.upper(),String.lower(),String.title(),String.find(element),String.count(element),String.isalpha(),String.isdigit(),String.islower(),String.isupper()
#Loop:
def myFun(arg1, *argv):
print ("First argument :", arg1)
for arg in argv:
print("Next argument through *argv :", arg)
> myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')
*argv - takes care of remaining parameters,except 'Hello' i.e non-keyworded, variable-length argument list.
b. List : It's collection of one or more data types, enclosed with in [] and each element is separated by comma. for example: ['rakesh',26,{1:'rakesh',2:'rupesh'},{1,2,3,1,4},[1,2,3,4]]
Operations:
+ Concatenation,* Repetition,[] slice,[ : ] - Range slice,in,not in
Built-In Functions:
len(List),max(List),min(List),List.append(element),List.insert(position,element),List.remove(element),List.pop() #Removes and returns the last object in the list.
,List.reverse(),List.sort(),List.sort(reverse=True) #Descending order
c. Tuple : It's collection of one or more data types, enclosed with in [] and each element is separated by comma. for example: ('rakesh',26,{1:'rakesh',2:'rupesh'},{1,2,3,1,4},[1,2,3,4])
Operations:
+ Concatenation,* Repetition,[] slice,[ : ] - Range slice,in,not in
Built-In Functions:
len(Tuple),max(Tuple),min(Tuple)
Note # Tuple is immutable. So, once a tuple is created, any operation that seeks to change its contents are not allowed.
#Common error # TypeError: 'tuple' object does not support item assignment
Conversion:
list('Python') ['P', 'y', 't', 'h', 'o', 'n']
tuple('Python') ('P', 'y', 't', 'h', 'o', 'n')
tuple(['rakesh',26,{1:'rakesh',2:'rupesh'},{1,2,3,1,4},[1,2,3,4]]) ('rakesh', 26, {1: 'rakesh', 2: 'rupesh'}, {1, 2, 3, 4}, [1, 2, 3, 4])
list(('rakesh', 26, {1: 'rakesh', 2: 'rupesh'}, {1, 2, 3, 4}, [1, 2, 3, 4])) ['rakesh', 26, {1: 'rakesh', 2: 'rupesh'}, {1, 2, 3, 4}, [1, 2, 3, 4]]
4. Dictionary
A dictionary object is an unordered collection of data in a key:value pair form,enclosed within {}. for example : {key1:value1,key2:value2,....so on}
>Sibling = {1:'Rakesh','SecondSibling':'Rupesh',3:'Ritesh','Sister':'Puja'}
Note : 1. Key should be an immutable object . So a number, string or tuple can be used as key. List can't be used as a key but it can be used as a value.
2. If the key appears more than once, only the last will be retained.
Operations & Built-In Functions:
Dictionary is not an ordered collection, so a value cannot be accessed using an index in square brackets.
> Sibling['SecondSibling'] or Sibling.get('SecondSibling') #'Rupesh'
> Sibling['SecondSibling'] = 'Ranjan' #Update
> Sibling['Cousin'] ='Ramesh' or Sibling.update({"Cousin":"Ramesh"}) #Addition of a new key:value pair
> Sibling.items() #dict_items([(1, 'Rakesh'), ('SecondSibling', 'Rupesh'), (3, 'Ritesh'), ('Sister', 'Puja'), ('Cousin', 'Ramesh')])
#Returns a list of tuples, each tuple containing the key and value of each pair.
> Sibling.keys() #dict_keys([1, 'SecondSibling', 3, 'Sister','Cousin'])
> Sibling.values() #dict_values(['Rakesh', 'Rupesh', 'Ritesh', 'Puja','Ramesh'])
> del Sibling['Cousin'] #delete a key:value pair
> del Sibling # delete dictionary object
len(Dictionary) #Returns the number of key:value pairs in the dictionary.
max(Dictionary) # Returns highest key
min(Dictionary) #Returns lowest key
Sibling.pop('Cousin') # Returns the value associated with the key and the corresponding key-value pair is removed.
Cousin = {4:'Ramesh',5:'Ranjan'}
Sibling.update(Cousin) # Now Sibling dictionary consist of Sibling and Cousin.
Sibling.clear() # Returns empty object by deleting all the key-value pairs.
Conversion:
#To convert to dictionary, each element must be a pair
> dict([[1,2],[3,4]]) #{1: 2, 3: 4}
> dict([(3,26),(4,44)]) #{3: 26, 4: 44}
Loop:
Sibling = {1:'Rakesh','SecondSibling':'Rupesh',3:'Ritesh','Sister':'Puja'}
for i in Sibling:
print('Key:',i)
print('Value:',Sibling.get(i))
o/p:
Key: 1
Value: Rakesh
Key: SecondSibling
Value: Rupesh
Key: 3
Value: Ritesh
Key: Sister
Value: Puja
def myFun(**kwargs):
for key, value in kwargs.items():
print ("%s == %s" %(key, value))
# Driver code
myFun(first ='Rakesh', mid ='R', last='Gupta')
o/p:
last == Gupta
mid == R
first == Rakesh
**kwargs - keyworded, variable-length argument list.
***Mutable and Immutable Objects***
1.Number values, strings and tuple are immutable, which means their contents can't be altered after creation.
2.It is possible to add, delete, insert, and rearrange items in a list or dictionary. Hence, they are mutable objects.
5. Set:
A set object contains one or more items, not necessarily of the same type, which are separated by comma and enclosed in curly brackets {}.
A set object has suitable methods to perform mathematical set operations like union, intersection, difference, etc.
It's unordered collection data of same or different type.
It stores only unique value.
Indexing and slicing operations cannot be done on a set object
set = {value1, value2, value3,...valueN}
A set object can be constructed out of any sequence such as a string, list or a tuple object
for example,
s1=set("Python") # {'o', 't', 'h', 'P', 'n', 'y'}
s2=set([45,67,87,36, 55]) # {67, 36, 45, 87, 55}
s3=set((10,25,15)) #{25, 10, 15}
Only Numbers (integer, float, as well as complex), strings, and tuple objects can be a part of a set object, but list and dictionary objects are not.
Operations:
Union : s1|s2 or s1.union(s2) # all elements from both s1 & s2
intersection : s1&s2 or s1.intersection(s2) # common elements from both s1 & s2
difference : s1-s2 or s1.difference(s2) # elements only in s1,not in s2
Symmetric Difference: s1^s2 or s1.symmetric_difference(s2) # s1.union(s2) - s1.intersection(s2)
Built-In Functions:
s1.add(element)
#Adds multiple items from a list or a tuple.
> S1={"Python", "Java", "C++"}
> S1.update(["C", "Basic"]) #{'C++', 'Java', 'Python', 'Basic', 'C'}
> S1.update(("Ruby", "PHP")) #{'C++', 'Ruby', 'Java', 'PHP', 'Python', 'Basic', 'C'}
> S1.clear() #Removes the contents of set object and results in an empty set.
> S2=S1.copy() #Creates a copy of the set object
#No changes are done if the item is not present.
> S1.discard("Java") #{'C++', 'Ruby', 'PHP', 'Python', 'Basic', 'C'} #Returns a set after removing an item from it.
> S1.remove("C++") #Returns a set after removing an item from it. Results in an error if the item is not present.
Loop:
language = {'C++', 'Ruby', 'Java', 'PHP', 'Python', 'Basic', 'C'}
for i in language:
print('language:',i)
o/p:
language: Java
language: Python
language: PHP
language: Ruby
language: Basic
language: C++
language: C
#RR #Day4 #Python #DataTypes #DataScience #HappyLearning #WeLearnEveryday
#list [] tuple () dictionary {key:value} set {}
#immutable objects - Number values, strings and tuple
#mutable objects - list and dictionary
These are built-in data types in Python:
1. Numeric
a. Integer - # type(7) <class 'int'>
b. Float - a real number with a fractional component #type(7.0) <class 'float'>
c. Complex Number - a + bj where a and b are floats and j is -1(square root of -1 called an imaginary number) #type(5+6j) <class 'complex'>
Conversion:
> int(7.5) 7
> float(7) 7.0
> complex(7.5) (7.5+0j)
> float(5+6j) TypeError: can't convert complex to float
Operations:
+ (Addition),- (Subtraction),* (Multiplication),/ (Division),% (Modulus),** (Exponent),// (Floor Division)
Built-In Functions:
int,float,complex,hex,oct,pow,abs,round.
2. Boolean
This datatype is mainly used in IF-ELSE statement. for example: 5 > 4 True
Conversion:
bool(7) True bool(5+4j) True bool('rakesh') True bool([]) False
bool(['rakesh']) True bool({}) False bool(('rakesh')) True and so on
3. Sequence Type: A sequence is an ordered collection of similar or different data types.Its element can be fetched using indices.
a. String : It's a collect of character(s) enclosed within a single,double or triple quotes. for example: 'Rakesh'
Operations:
+,*,Slicing Operator: []/[:],in,not in
Built-In Functions:
String.capitalize(),String.upper(),String.lower(),String.title(),String.find(element),String.count(element),String.isalpha(),String.isdigit(),String.islower(),String.isupper()
#Loop:
def myFun(arg1, *argv):
print ("First argument :", arg1)
for arg in argv:
print("Next argument through *argv :", arg)
> myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')
*argv - takes care of remaining parameters,except 'Hello' i.e non-keyworded, variable-length argument list.
b. List : It's collection of one or more data types, enclosed with in [] and each element is separated by comma. for example: ['rakesh',26,{1:'rakesh',2:'rupesh'},{1,2,3,1,4},[1,2,3,4]]
Operations:
+ Concatenation,* Repetition,[] slice,[ : ] - Range slice,in,not in
Built-In Functions:
len(List),max(List),min(List),List.append(element),List.insert(position,element),List.remove(element),List.pop() #Removes and returns the last object in the list.
,List.reverse(),List.sort(),List.sort(reverse=True) #Descending order
c. Tuple : It's collection of one or more data types, enclosed with in [] and each element is separated by comma. for example: ('rakesh',26,{1:'rakesh',2:'rupesh'},{1,2,3,1,4},[1,2,3,4])
Operations:
+ Concatenation,* Repetition,[] slice,[ : ] - Range slice,in,not in
Built-In Functions:
len(Tuple),max(Tuple),min(Tuple)
Note # Tuple is immutable. So, once a tuple is created, any operation that seeks to change its contents are not allowed.
#Common error # TypeError: 'tuple' object does not support item assignment
Conversion:
list('Python') ['P', 'y', 't', 'h', 'o', 'n']
tuple('Python') ('P', 'y', 't', 'h', 'o', 'n')
tuple(['rakesh',26,{1:'rakesh',2:'rupesh'},{1,2,3,1,4},[1,2,3,4]]) ('rakesh', 26, {1: 'rakesh', 2: 'rupesh'}, {1, 2, 3, 4}, [1, 2, 3, 4])
list(('rakesh', 26, {1: 'rakesh', 2: 'rupesh'}, {1, 2, 3, 4}, [1, 2, 3, 4])) ['rakesh', 26, {1: 'rakesh', 2: 'rupesh'}, {1, 2, 3, 4}, [1, 2, 3, 4]]
4. Dictionary
A dictionary object is an unordered collection of data in a key:value pair form,enclosed within {}. for example : {key1:value1,key2:value2,....so on}
>Sibling = {1:'Rakesh','SecondSibling':'Rupesh',3:'Ritesh','Sister':'Puja'}
Note : 1. Key should be an immutable object . So a number, string or tuple can be used as key. List can't be used as a key but it can be used as a value.
2. If the key appears more than once, only the last will be retained.
Operations & Built-In Functions:
Dictionary is not an ordered collection, so a value cannot be accessed using an index in square brackets.
> Sibling['SecondSibling'] or Sibling.get('SecondSibling') #'Rupesh'
> Sibling['SecondSibling'] = 'Ranjan' #Update
> Sibling['Cousin'] ='Ramesh' or Sibling.update({"Cousin":"Ramesh"}) #Addition of a new key:value pair
> Sibling.items() #dict_items([(1, 'Rakesh'), ('SecondSibling', 'Rupesh'), (3, 'Ritesh'), ('Sister', 'Puja'), ('Cousin', 'Ramesh')])
#Returns a list of tuples, each tuple containing the key and value of each pair.
> Sibling.keys() #dict_keys([1, 'SecondSibling', 3, 'Sister','Cousin'])
> Sibling.values() #dict_values(['Rakesh', 'Rupesh', 'Ritesh', 'Puja','Ramesh'])
> del Sibling['Cousin'] #delete a key:value pair
> del Sibling # delete dictionary object
len(Dictionary) #Returns the number of key:value pairs in the dictionary.
max(Dictionary) # Returns highest key
min(Dictionary) #Returns lowest key
Sibling.pop('Cousin') # Returns the value associated with the key and the corresponding key-value pair is removed.
Cousin = {4:'Ramesh',5:'Ranjan'}
Sibling.update(Cousin) # Now Sibling dictionary consist of Sibling and Cousin.
Sibling.clear() # Returns empty object by deleting all the key-value pairs.
Conversion:
#To convert to dictionary, each element must be a pair
> dict([[1,2],[3,4]]) #{1: 2, 3: 4}
> dict([(3,26),(4,44)]) #{3: 26, 4: 44}
Loop:
Sibling = {1:'Rakesh','SecondSibling':'Rupesh',3:'Ritesh','Sister':'Puja'}
for i in Sibling:
print('Key:',i)
print('Value:',Sibling.get(i))
o/p:
Key: 1
Value: Rakesh
Key: SecondSibling
Value: Rupesh
Key: 3
Value: Ritesh
Key: Sister
Value: Puja
def myFun(**kwargs):
for key, value in kwargs.items():
print ("%s == %s" %(key, value))
# Driver code
myFun(first ='Rakesh', mid ='R', last='Gupta')
o/p:
last == Gupta
mid == R
first == Rakesh
**kwargs - keyworded, variable-length argument list.
***Mutable and Immutable Objects***
1.Number values, strings and tuple are immutable, which means their contents can't be altered after creation.
2.It is possible to add, delete, insert, and rearrange items in a list or dictionary. Hence, they are mutable objects.
5. Set:
A set object contains one or more items, not necessarily of the same type, which are separated by comma and enclosed in curly brackets {}.
A set object has suitable methods to perform mathematical set operations like union, intersection, difference, etc.
It's unordered collection data of same or different type.
It stores only unique value.
Indexing and slicing operations cannot be done on a set object
set = {value1, value2, value3,...valueN}
A set object can be constructed out of any sequence such as a string, list or a tuple object
for example,
s1=set("Python") # {'o', 't', 'h', 'P', 'n', 'y'}
s2=set([45,67,87,36, 55]) # {67, 36, 45, 87, 55}
s3=set((10,25,15)) #{25, 10, 15}
Only Numbers (integer, float, as well as complex), strings, and tuple objects can be a part of a set object, but list and dictionary objects are not.
Operations:
Union : s1|s2 or s1.union(s2) # all elements from both s1 & s2
intersection : s1&s2 or s1.intersection(s2) # common elements from both s1 & s2
difference : s1-s2 or s1.difference(s2) # elements only in s1,not in s2
Symmetric Difference: s1^s2 or s1.symmetric_difference(s2) # s1.union(s2) - s1.intersection(s2)
Built-In Functions:
s1.add(element)
#Adds multiple items from a list or a tuple.
> S1={"Python", "Java", "C++"}
> S1.update(["C", "Basic"]) #{'C++', 'Java', 'Python', 'Basic', 'C'}
> S1.update(("Ruby", "PHP")) #{'C++', 'Ruby', 'Java', 'PHP', 'Python', 'Basic', 'C'}
> S1.clear() #Removes the contents of set object and results in an empty set.
> S2=S1.copy() #Creates a copy of the set object
#No changes are done if the item is not present.
> S1.discard("Java") #{'C++', 'Ruby', 'PHP', 'Python', 'Basic', 'C'} #Returns a set after removing an item from it.
> S1.remove("C++") #Returns a set after removing an item from it. Results in an error if the item is not present.
Loop:
language = {'C++', 'Ruby', 'Java', 'PHP', 'Python', 'Basic', 'C'}
for i in language:
print('language:',i)
o/p:
language: Java
language: Python
language: PHP
language: Ruby
language: Basic
language: C++
language: C
#RR #Day4 #Python #DataTypes #DataScience #HappyLearning #WeLearnEveryday
Comments
Post a Comment