You are on page 1of 44

Data Types in Python

Contents
• Data Types in Python
• Python Numbers
• Python Strings
• Python List
• Python Tuple
• Python Set
• Python Dictionary
• Conversion between data types

12/1/2021 2
Data types in Python
• Every value in Python has a datatype. Since everything is an object in Python programming, data
types are actually classes and variables are instance (object) of these classes.

• The data type determines:


 The possible values for that type.
 The operations that can be done with that values.
 Conveys the meaning of data.
 The way values of that type can be stored.

• There are various data types in Python. Some of the important types are listed below.
– Python Numbers
– Python Strings
– Python List
– Python Tuple
– Python Set
– Python Dictionary
12/1/2021 3
Python Numbers
a=5
print(a, "is of type", type(a))
• Integers, floating point numbers and complex
a = 2.0
numbers falls under Python numbers category.
print(a, "is of type", type(a))
• They are defined as int, float and complex class in a = 1+2j
Python. print(a, "is complex number?",
• We can use the type() function to know which class isinstance(1+2j,complex))
a variable or a value belongs to and #Output
the isinstance() function to check if an object 5 is of type <class 'int'>
belongs to a particular class. 2.0 is of type <class 'float'>
• Integers can be of any length, it is only limited by (1+2j) is complex number? True
the memory available.
• A floating point number is accurate up to 15 myfloat = 7.0
decimal places. Integer and floating points are print(myfloat)
separated by decimal points. 1 is integer, 1.0 is myfloat = float(7)
floating point number. print(myfloat)
#Output 7.0
7.0
12/1/2021 4
Python Strings
• String is sequence of Unicode characters. We can mystring = 'hello‘
use single quotes or double quotes to represent print(mystring)
mystring = "hello“
strings. Multi-line strings can be denoted using print(mystring)
triple quotes, ''' or """. #Output hello
hello
• The difference between the two is that using double
quotes makes it easy to include apostrophes ( ‘ )
(whereas these would terminate the string if using s = 'Hello world’
print("s[4] = ", s[4])
single quotes) print("s[6:11] =",s[6:11])
• Use [ ] to access characters in a string. #Output s[4] = o
s[6:11] = world
• Slicing Use [ # : # ] to get set of letters.

12/1/2021 5
Python String Functions
For understanding the string functions; consider a variable word=“Hello World”

Function Use Syntax Example Output


len() Length of the String len(string variable) len(word) 11
count() Returns the count of the Number print(word.count('l')) 3
number of occurrences of a StringVariable.count(letter)
letter
find() Returns the position of a letter Number StringVariable.find( print(word.find('W')) 6
or string in the given string. substring)
Returns -1 if not present
index() Returns the index of substring Number print(word.index('Wo')) 6
if present, else returns error StringVariable.index(substring)
split() Splits the string on splitting List word.split('o') ['Hell', '
character StringVariable.split(character) W',
'rld']

12/1/2021 6
Python String Functions(Contd.)

Function Use Syntax Example Output


startswith( Checks if string starts with the Boolean word.startswith('H') True
) given character startswith(StringVariable)
endswith() Checks if string ends with the Boolean word.endswith(‘d') True
given character endswith(StringVariable)
Repeat character Repeats the character for print("."*5) …..
specified number of times.
replace() Replace the substring with SttringVariable.replace(string1 word.replace('Hello','Hi') 'Hi
another ,string2) World'
upper() Converts the string to upper StringVariable.upper() word.upper() 'HELLO
case WORLD'
lower() Converts the string to lower StringVariable.upper() Word.lower() ‘hello
case world’

12/1/2021 7
Python String Functions(Contd.)
Function Use Syntax Example Output
strip() Eliminates the white spaces StringVariable.strip() Word=“ hi “ hi
Word.strip()
lstrip() Eliminates the white spaces from StringVariable.lstrip() Word.lstrip() ‘hi ‘
the left of the string if any.
rstrip() Eliminates the white spaces from StringVariable.rstrip() Word.rstrip() ‘ hi‘
the right of the string if any.
join() Adds specified character after Character.join(StringVari "*".join(word) 'H*e*l*l*o*
every letter of the string. able) *W*o*r*l*d'
swapcase() Swaps the case of each character StringVariable.swapcase word.swapcase() 'hELLO wORLD'
()
title() Convert the string to tile case StringVariable.title() word.title() 'Hello World’
capitalize() Capitalize first letter StringVariable.Capitalize word.capitalize() 'Hello World’
()
12/1/2021 8
List (Mutable)
• Lists are very similar to arrays.
• They can contain any type of variable, and they can contain as many variables
as you wish.
• Lists can also be iterated over in a very simple manner.
• Here is an example of how to build a list.
thislist = ["apple", "banana", "cherry"]
Creation of list print(thislist)
#Output ['apple', 'banana', 'cherry']

print(thislist[0])
Access list elements #Output apple

thislist[1] = "blackcurrant"
Change item value print(thislist)
#Output ['apple', 'blackcurrant', 'cherry']

12/1/2021 9
List (contd.)
result = "apple" in thislist
Check presence of
print(result)
individual item – #Output True
in operator
print(len(thislist))
Number of items
#Output 3
In list -- len()
thislist.append("orange")
Adding items to print(thislist)
The list – append() #Output ['apple', 'blackcurrant', 'cherry', 'orange']

thislist.insert(2, "mango")
Adding items to
print(thislist)
The list at any position #Output ['apple', 'blackcurrant', 'mango', 'cherry', 'orange']
-- insert()
12/1/2021 10
List (contd.)
thislist.remove("cherry")
Remove an element
print(thislist)
From the list – remove() #Output ['apple', 'blackcurrant', 'mango', 'orange']

Remove last item thislist.pop()


print(thislist)
From list-- pop() #Output ['apple', 'blackcurrant', 'mango']

Remove item from thislist.pop(1)


list at specific print(thislist)
#Output ['apple', 'mango']
position-- pop(x)
del thislist[0] # to delete complete list
Remove item from print (thislist) del thislist
list at specific position-- del(x) #Output ['mango']
thislist.clear()
Delete all the print (thislist)
Elements of the list -- clear #Output []
12/1/2021 11
List (contd.)
thislist = ["apple", "banana", "cherry"]
Copy one list to mylist = thislist.copy()
Another – copy() print(mylist)
#Output ['apple', 'banana', 'cherry']
thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
Copy one list to
print(mylist)
Another – list() #Output ['apple', 'banana', 'cherry']

thislist.reverse()
Reverse the content print(thislist)
Of list– reverse() #Output ['cherry', 'banana', 'apple']

thislist.sort()
Sorting the items
print(thislist)
Of list -- sort() #Output ['apple', 'banana', 'cherry']

12/1/2021 12
List (contd.)

Get index of the thislist.index('banana')


Required element– index() #Output 1

Get count of occurrences thislist.count('banana')


Of the list element #Output 1

– count()

12/1/2021 13
Tuples
A tuple is a collection which is ordered and unchangeable. Tuples are immutable.
Tuples once created cannot be modified. Tuples are used to write-protect data and
are usually faster than list as it cannot change dynamically.
thistuple = ("apple", "banana", "cherry")
Create a tuple print(thistuple)
#Output ('apple', 'banana', 'cherry')
thistuple = tuple(("apple", "banana", "cherry"))
Create a tuple # note the double round-brackets
Using constructor print(thistuple)
#Output ('apple', 'banana', 'cherry')

Delete a tuple del thistuple


-- del() #Output

12/1/2021 14
Tuples (Contd.)

To determine
print(len(thistuple))
how many items a
#Output 3
tuple has -- len()
thistuple = ("apple", "banana", "cherry")
Check presence of if "apple" in thistuple:
individual item – print("Yes, 'apple' is in the fruits tuple")
#Output Yes, 'apple' is in the fruits tuple
in operator
print(thistuple[0])
Access specific item #Output apple

12/1/2021 15
Tuples (Contd.)

print(thistuple[0])
Access specific item #Output apple

Returns the number


thistuple = (1,2,3,2,5,6,1,7)
of times a specified print( thistuple.count(2))
value occurs in a tuple – #Output 2
Count()
Searches the tuple
for a specified value thistuple = (1,2,3,2,5,6,1,7)
print(thistuple.index(5))
and returns the #Output 4
position of where
it was found – index()
12/1/2021 16
Sets
Set is an unordered collection of unique items. Set is defined by values separated by
comma inside braces { }. Items in a set are not ordered. We can perform set
operations like union, intersection on two sets. Set have unique values. They
eliminate duplicates. Since, set are unordered collection, indexing has no meaning.
Hence the slicing operator [] does not work.

a = {5,2,3,1,4}
# printing set variable
Creating and displaying
print("a = ", a)
set # data type of variable a
print(type(a))
#Output a = {1, 2, 3, 4, 5}
<class 'set'>

12/1/2021 17
Sets (contd.)
a = {5,2,3,1,4,1,2,2}
Set have
print("a = ", a)
unique values #Output a = {1, 2, 3, 4, 5}

Check presence of thisset = {"apple", "banana", "cherry"}


individual item – print("banana" in thisset)
in operator # True

Number of items print(len(thisset))


In list -- len() #Output 3

12/1/2021 18
Sets (contd.)
Adding element to set

thisset.add("mango")
Adding element print(thisset)
To set – add() #Output {'banana', 'cherry', 'apple', 'mango'}

Adding multiple thisset = {"apple", "banana", "cherry"}


thisset.update(['orange','strawberry'])
Items in set print(thisset)
--update #Output {'strawberry', 'banana', 'orange', 'cherry', 'apple'}

12/1/2021 19
Sets (contd.)
Removing element to set

thisset.remove('banana')
Remove an element print(thisset)
From set –remove() #Output {'strawberry', 'orange', 'cherry', 'apple'}
Does not give error, if
element does no exist
thisset.discard('apple')
Remove an element
print(thisset)
From set –discard() #Output {'strawberry', 'orange', 'cherry'}

x= thisset.pop()
Remove the last element print(x)
From set –pop() print(thisset)
#Output strawberry
{'orange', 'cherry'}

12/1/2021 20
Sets (contd.)
Removing element to set

a.clear()
Remove all elements print(a)
From set –clear() #Output set()

del thisset
Delete the set #Output
–del()

12/1/2021 21
Sets (contd.)
Set operations a={1,2,3,4,5} b={4,5,6,7,8}
c=a.union(b)
Union of 2 sets–union() print(c)
#Output {1, 2, 3, 4, 5, 6, 7, 8}

Intersection of two sets c=a.intersection(b)


–intersection() print(c)
#Output {4, 5}​

Difference of two sets c=a.difference(b)


–difference() print(c)
#Output {1, 2, 3}

12/1/2021 22
Sets (contd.)
Set operators
Operator Meaning
key in s containment check
s1 == s2 key not in s ; non-containment check
s1 != s2 s1 is not equivalent to s2
s1 <= s2 s1is subset of s2
s1 < s2 s1 is proper subset of s2
s1 >= s2 s1is superset of s2
s1 > s2 s1 is proper superset of s2
s1 | s2 the union of s1 and s2
s1 & s2 the intersection of s1 and s2
s1 – s2 the set of elements in s1 but not s2
s1 ˆ s2 the set of elements in precisely one of s1 or s2

12/1/2021 23
Dictionary
• Dictionary in Python is an unordered collection of data values, used to
store data values like a map, which unlike other Data Types that hold only
single value as an element, Dictionary holds key:value pair.
• Key value is provided in the dictionary to make it more optimized.
• Each key-value pair in a Dictionary is separated by a colon :, whereas each
key is separated by a ‘comma’.
• A Dictionary in Python works similar to the Dictionary in a real world.
• Keys of a Dictionary must be unique and of immutable data type such as
Strings, Integers and tuples, but the key-values can be repeated and be of
any type.
• Note – Keys in a dictionary doesn’t allows Polymorphism.

12/1/2021 24
Dictionary (Contd.)
Python dictionary can be created using various ways.
• Dictionary with the use of dict(): {1: 'Geeks', 2: 'For', 3: 'Geeks'}
• Empty Dictionary: {}
• # Creating an empty Dictionary • # Creating a Dictionary with dict() method
• Dict = {} • Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'})
• print("Empty Dictionary: “, Dict) • print("\nDictionary with the use of dict(): “, Dict)

• Dictionary with the use of Integer Keys: {1: ‘Python', 2:


‘Dictionary', 3: ‘Demo'} • Dictionary with each item as a pair: {1: 'Geeks', 2: 'For'}
• # Creating a Dictionary with Integer Keys
• Dict = {1: ‘Python', 2: 'For', 3: 'Geeks'} • # Creating a Dictionary with each item as a Pair
• print("\nDictionary with the use of Integer Keys: “, Dict) • Dict = dict([(1, 'Geeks'), (2, 'For')])
• • print("\nDictionary with each item as a pair: “, Dict)
• Dictionary with the use of Mixed Keys: {'Name': 'Geeks', 1: [1,
2, 3, 4]}
• # Creating a Dictionary with Mixed keys
• Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
• print("\nDictionary with the use of Mixed Keys: “, Dict)

12/1/2021 25
Dictionary (Contd.)
Nested Dictionary
• Dict = {1: 'Geeks', 2: 'For',
• 3:{'A' : 'Welcome', 'B' : 'To',
'C' : 'Geeks'}}

• print(Dict)
• Output:
• {1: 'Geeks', 2: 'For', 3: {'A':
'Welcome', 'B': 'To', 'C': 'Geeks'}}

12/1/2021 26
Dictionary (Contd.)
Adding Element to dictionary
• Dict = {} • Output:
• # Adding elements one at a time • Dictionary after adding 2 elements: {0: 'Geeks', 1: 'For'}
• Dict[0] = 'Geeks' • Dictionary after adding 3 elements: {0: 'Geeks', 1: 'For',
• Dict[1] = 'For' 'Value_set': (2, 3, 4)}
• print("\nDictionary after adding 2 elements: “, Dict) • Updated key value: {0: 'Geeks', 1: 'For', 'Value_set': (2, 3,
• # Adding set of values to a single Key 4), 2: 'Welcome'}
• Dict['Value_set'] = 2, 3, 4 • Adding a Nested Key: {0: 'Geeks', 1: 'For', 'Value_set': (2, 3,
• print("\nDictionary after adding 3 elements: “,Dict) 4), 2: 'Welcome', 5: {'Nested': {'1': 'Life', '2': 'Geeks'}}}
• # Updating existing Key's Value
• Dict[2] = 'Welcome'
• print("\nUpdated key value: “, Dict)
• # Adding Nested Key value to Dictionary
• Dict[5] = {'Nested' :{'1' : 'Life', '2' : 'Geeks'}}
• print("\nAdding a Nested Key: “, Dict)

12/1/2021 27
Dictionary (Contd.)
Access Elements

• # accessing a element using key • Output:


• print("Accessing a element using key:") • Accessing a element using key:
• print(Dict['name']) • For
• • Accessing a element using key:
• # accessing a element using key • Geeks
• print("Accessing a element using key:") • Accessing a element using get:
• print(Dict[1]) • Geeks

• # accessing a element using get() method
• print("Accessing a element using get:")
• print(Dict.get(3))

12/1/2021 28
Dictionary (Contd.)
Remove Elements • Initial Dictionary: {5: 'Welcome', 6: 'To', 7: 'Geeks', 'A': {1: 'Geeks', 2: 'For', 3:
'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}}
• # Initial Dictionary
• Deleting a specific key: {5: 'Welcome', 7: 'Geeks', 'A': {1: 'Geeks', 2: 'For', 3:
• Dict = { 5 : 'Welcome', 6 : 'To', 7 : 'Geeks', 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}}
• 'A' : {1 : 'Geeks', 2 : 'For', 3 : 'Geeks'}, • Deleting a key from Nested Dictionary: {5: 'Welcome', 7: 'Geeks', 'A': {1:
• 'B' : {1 : 'Geeks', 2 : 'Life'}} 'Geeks', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}} {5: 'Welcome', 7: 'Geeks', 'A': {1:
• print("Initial Dictionary: ",Dict) 'Geeks', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}}
• # Deleting a Key value • Popping specific element: {7: 'Geeks', 'A': {1: 'Geeks', 3: 'Geeks'}, 'B': {1:
• del Dict[6] 'Geeks', 2: 'Life'}}
• print("\nDeleting a specific key: ", Dict) • Pops first element: {7: 'Geeks', 'A': {1: 'Geeks', 3: 'Geeks'}}
• # Deleting a Key from Nested Dictionary • Deleting Entire Dictionary: {}
• del Dict['A'][2]
• print("\nDeleting a key from Nested Dictionary: ", Dict)
• print(Dict)
• # Deleting a Key using pop()
• Dict.pop(5)
• print("\nPopping specific element: ", Dict)
• Dict.popitem()
• print("\nPops first element: ", Dict)
• # Deleting entire Dictionary
• Dict.clear()
• print("\nDeleting Entire Dictionary: ", Dict)

12/1/2021 29
Dictionary (Contd.)
thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 }

METHODS DESCRIPTION SYNTAX OUTPUT


They copy() method returns a shallow copy {'brand': 'Ford', 'model': 'Mustang',
copy() mydict = thisdict.copy()
of the dictionary. 'year': 1964}
dictionary_na returns a list of all the values available in a
mydict.values() dict_values(['Ford', 'Mustang', 1964])
me.values() given dictionary.
Adds dictionary dict2’s key-values pairs to {'brand': 'Ford', 'model': 'Mustang',
update() mydict.update({4:"Nexa"})
dict 'year': 1964, 4: 'Nexa'}
keys() Returns list of dictionary dict’s keys mydict.keys() dict_keys(['brand', 'model', 'year', 4])
dict_items([('brand', 'Ford'), ('model',
items() Returns a list of dict’s (key, value) tuple pairs mydict.items()
'Mustang'), ('year', 1964), (4, 'Nexa')])
Len() Returns length of dictionary len(mydict) 4
"{'brand': 'Ford', 'model': 'Mustang',
Str() Returns string type of dictionary Str(mydict)
'year': 1964, 4: 'Nexa'}"

12/1/2021 30
Real Life Examples Of Data Types
• List : You can use a List to store the steps necessary to cook a chicken,
because Lists support sequential access and you can access the steps in
order.
• Tuple : You can use a Tuple to store the latitude and longitude of your
home, because a tuple always has a predefined number of elements (in
this specific example, two). The same Tuple type can be used to store the
coordinates of other locations.
• Set : You can use a Set to store passport numbers, because a Set enforces
uniqueness among its elements. Passport numbers are always unique and
two people can't have the same one.
• Dictionary : Dictionary in Python gives a very intuitive way to organize
data. e.g. in a phone book dictionary you can easily map a name to the
phone numbers a person is having.
12/1/2021 31
Programs
1. Python program to interchange first and last elements in a list.
Input : [1, 2, 3] Output : [3, 2, 1]
2. Python program to swap two elements in a list.
Input : List = [23, 65, 19, 90], pos1 = 1, pos2 = 3 Output : [19, 65, 23, 90]
4. Python program to create a list of tuples from given list having number
and its cube in each tuple
Input: list = [1, 2, 3] Output: [(1, 1), (2, 8), (3, 27)]
5. Remove all duplicates from a given string in Python
Input : aeeekksswwnnu Output : aekswnu
6. Python program for Lowercase first character of String without using
function.
12/1/2021 32
Python program to interchange first and last
elements in a list.
• newList = [12, 35, 9, 56, 24]
• first = newList.pop(0)
• last = newList.pop(-1)
• newList.insert(0, last)
• newList.append(first)
• Print(newList)

12/1/2021 33
Python program to swap two elements in a list.

• list = [23, 65, 19, 90]


• pos1, pos2 = 1, 3
• list[pos1], list[pos2] = list[pos2], list[pos1]
• Print(list)

12/1/2021 34
Python program to create a list of tuples from given
list having number and its cube in each tuple
• # creating a list
• list1 = [1, 2, 5, 6]

• # using list comprehension to iterate each
• # values in list and create a tuple as specified
• res = [(val, pow(val, 3)) for val in list1]

• # print the result
• print(res)

12/1/2021 35
Remove all duplicates from a given string in Python
• str1 = "geeksforgeeks"
• print("".join(set(str1)))

12/1/2021 36
Type Conversion
• The process of converting the value of one data type (integer, string,
float, etc.) to another data type is called type conversion. Python has
two types of type conversion.
– Implicit Type Conversion  In Implicit type conversion, Python automatically
converts one data type to another data type. This process doesn't need any user
involvement.
– Explicit Type Conversion In Explicit Type Conversion, users convert the data
type of an object to required data type. We use the predefined functions
like int(), float(), str(), etc to perform explicit type conversion.

12/1/2021 37
Implicit Type Conversion
x_int = 123 x_int = 123
y_float = 12.3 y_float = 12.3
print("type of x_int", type(x_int)) print("type of x_int", type(x_int))
print("type of y_float",type(y_float)) print("type of y_float",type(y_float))
x_int = y_float y_float = x_int
print ("New value and type of x_int", x_int , print ("New value and type of y_float", y_float ,
type(x_int)) type(y_float))

type of x_int <class 'int'> type of x_int <class 'int'>


type of y_float <class 'float'> type of y_float <class 'float'>
New value and type of x_int 12.3 <class 'float'> New value and type of y_float 123 <class 'int'>

12/1/2021 38
Implicit Type Conversion
• s = '4' • After converting character to integer : 52
• • After converting 56 to hexadecimal string : 0x38
• # printing character converting to integer • After converting 56 to octal string : 0o70
• c = ord(s)
• print ("After converting character to integer : ",end="")
• print (c)

• # printing integer converting to hexadecimal string
• c = hex(56)
• print ("After converting 56 to hexadecimal string : ",end="")
• print (c)

• # printing integer converting to octal string
• c = oct(56)
• print ("After converting 56 to octal string : ",end="")
• print (c)
12/1/2021 39
Type Conversion
• Converting to int type
– int(a,base) : This function converts any data type to integer. ‘Base’
specifies the base in which string is if data type is string.
s = "10010" s = "10010"
# printing string converting to int base 2 # printing string converting to int base 10
c = int(s,2) c = int(s,10)
print ("After converting to integer base 2 : ", end="") print ("After converting to integer base 10 : ", end="")
print (c) print (c)

After converting to integer base 2 : 18 After converting to integer base 10 : 10010

12/1/2021 40
Type Conversion - Explicit
• a=1 • After converting integer to complex number : (1+2j)
• b=2 • After converting integer to string : 1
• # initializing tuple • After converting tuple to dictionary : {'a': 1, 'f': 2, 'g': 3}
• tup = (('a', 1) ,('f', 2), ('g', 3))
• # printing integer converting to complex number
• c = complex(1,2)
• print ("After converting integer to complex number : ",end="")
• print (c)
• # printing integer converting to string
• c = str(a)
• print ("After converting integer to string : ",end="")
• print (c)
• # printing tuple converting to expression dictionary
• c = dict(tup)
• print ("After converting tuple to dictionary : ",end="")
• print (c)
12/1/2021 41
Type Conversion
• Addition of string and integer using explicit conversion
• num_int = 123
• num_str = "456“
• print("Data type of num_int:",type(num_int))
• print("Data type of num_str before Type Casting:",type(num_str))
• num_str = int(num_str)
• print("Data type of num_str after Type Casting:",type(num_str))
• num_sum = num_int + num_str
• print("Sum of num_int and num_str:",num_sum)
• print("Data type of the sum:",type(num_sum))
• Data type of num_int: <class 'int'>
• Data type of num_str before Type Casting: <class 'str'>
• Data type of num_str after Type Casting: <class 'int'>
• Sum of num_int and num_str: 579
• Data type of the sum: <class 'int'>

12/1/2021 42
Type Conversion – List and Tuple
• a_tuple = (1,2,3,4,5,6,7,8,9,10) • dessert = 'Cake'
b_list = [1,2,3,4,5] • # Convert the characters in a string
print(tuple(b_list)) #to individual items in a tuple
print(list(a_tuple)) print(tuple(dessert))
• # Convert a string into a list
• Output : dessert_list = list(dessert)
• (1, 2, 3, 4, 5) dessert_list.append('s')
• [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(dessert_list)
• Output :
• ('C', 'a', 'k', 'e')
• ['C', 'a', 'k', 'e', 's']

12/1/2021 43
12/1/2021 44

You might also like