Data Types in Python

 Print   10 min read  
02 Sep 2022
Beginner
2.89K Views

Data type is very important term in programming languages it classifies the variable. It tells what kind of values are acceptable for a particular variable and what mathematical, relational or logical operations we can perform without any errors. Python provides some basic data types as well some advance and very useful data types. Everything in Python is an object, variables are instance whereas data types are classes.We will discuss all major data types in Python in this article that are as follows.

Data Types

Number

Number can be an Integer, Float and Complex in Python. They are defined as int, float and complex class in Python.

type() :This function can be used to know which class a variable or a value belongs.

isinstance() :This function checks if an object belongs to a particular class.

Example
 
 b = 5
 print(b, "is of type", type(b))
 
 b = 22.05
 print(b, "is of type", type(b))
 
 b = 1+2j
 print(b, "is complex number?", isinstance(1+2j,complex))

Output

 (5, 'is of type', <type 'int'>)
 (22.05, 'is of type', <type 'float'>)
 ((1+2j), 'is complex number?', True)

Integers in Python are same as any other programming language. The only limitation is the memory available.Floating numbers are accurate upto 15 decimal places. Decimal numbers are separated by decimal points. 2 is an integer and 2.3 is float. Complex numbers are written as (x + 2j) where one is real and another one is imaginary part. Here ‘x’ is real part and ‘2j’ is our imaginary part.

Example
 >>> integer = 123456787465454813165
 >>> integer
 123456787465454813165
 >>> b = 0.1215487465415486
 >>> b
 0.1215487465415486
 >>> c = 1 + 2j
 >>> c
 (1+2j)

List

List is a data type in Python which you can relate to arrays in some other programming languages. But arrays are homogeneous means same type of variable you can store whereas in Python list are very flexible you can store any type of item in it. Declaring a Python list is very straight forward you just need to write all values comma separated inside square brackets.

Example 1

Suppose you want to store heights of a group then you can store them in list as belows :

 #Storing heights of persons in Height
 Height = [1.73 , 1.68, 1.76 ]

List items can be accessed by indices which starts from zero 0 for the first element and then continues incrementally.

Example 2

We will access our height list created earlier

 print(Height[0])
 
 #you want to store height and name both then
 Height = [“rahul”, 1.75, “person”, 1.63, “person2”, 1.96]

Nested List

You can even store list inside a list i.e. nested list.

Example 3: suppose we store heights of person as an individual sublist in list.

 
 Person_heights = [[“person1”, 1.75] , [“person2”, 1.68]]

List are mutable as we seen they can be accessed by index we can also manipulate them by assignment operator

Example 4
 Values = [ 1, 2, 3, 4,5, 6]
 Values[0] = 9
 print(Values)
Output
 
 [9, 2, 3, 4, 5, 6]

We can use slicing operator [ ] to get a subset list or a particular item. Slicing a very useful feature in Python

Example 5
 b= [5,10,15,20,25]
 
 #printing upto 3 indices
 print(b[:3])
 
 #reversing a list with use of slicing
 print(b[::-1])
 
 #printing from indices 1 to 3
 print(b[1:3])
 
 
 Output
 
 [5, 10, 15]
 [25, 20, 15, 10, 5]
 [10, 15]

You can read more on slicing just search on web. Below is a simple slicing notation which you can remember and play

 
 Slicing Notation
 [ <first element to include>: <first element to exclude> : <step> ]

Tuples

Tuples are ordered sequence. Tuples are written as a comma-separated elements within parentheses. Tuples once created can’t be modified that makes them faster as compared to list.

Example 5
 
 #Here we are declaring a tuple named score:
 Score = (20,30,55,68,12,32)
 
 #All the different types in Python - String, Integer, Float can all be contained in tuple.
 Tuple1 = (‘person’, 20, 12.5)

Each element of tuple can be accessed via index same as lists.

Index
Value
0
person
1
20
2
12.5
Accessing Tuples
 
 # accessing 0 index
 print(Tuple1[0])
 
 #Negative Index in Tuples
 print(Tuple1[-3:])
Output
 
 #We accessed same element first with zero index then negative index
 person 
 person

Note : bSlicing also works with tuples

Strings

Python string is a sequence of Unicode characters. Strings are represented as characters between single quote or double quote. Multiline strings are denoted by triple quotes ‘’’, or “””

Declaring a String
 str_var = “””STRING”””
 str2 = “i am string”

String also support the slicing operator after all its sequence of characters.

Example
 
 R = "Hello World"
 print("R[4] =", R[4]);
 print("R[1:3]=",R[1:3])
Output
 ('R[4] =', 'o')
 ('R[1:3]=', 'el')

Set

Sets are type of collections like list and tuples which means you can input different Python types. Sets are unordered whereas list and tuples are ordered collections. Sets don’t have any record for the element position they only contain unique elements.

Creating a set

You can create a set with curly braces and in between the elements you want to put.

Example
 Set1 = { 1, 2, 1, 3, 4, 5 }
 print(Set1)

You can see that we have kept a duplicate element inside set while declaring but when the actual set is created this element will be removed and you will get only unique elements.

Output
 set([1, 2, 3, 4, 5])

Adding an element in set

You can add element to a set using the function “add” If we add same item twice nothing will happen as sets can’t have any duplicate items. To remove an element we can use remove method

Example Set1 = { 1, 2, 3, 4, 5} Set1.add(6) print(Set1) Set1.remove(1) print(Set1) Output
 set([1, 2, 3, 4, 5, 6])
 set([2, 3, 4, 5, 6])

Dictionary

Dictionary is also an unordered collection in Python which has keys and values. Dictionaries are very good at data retrieval you just need to know the key. To create dictionary, we use curly brackets. The keys are the first element in and dictionary they are unique and immutable. Each key and value pairs are separated by colon on the left side is the key and right side is the value.

 
#Empty Dictionary declaration
>>> dict1 = {}
>>> dict2 = {"k":"value","two":2}
>>> type(dict2)
<class 'dict'>
>>>

Accessing elements of dictionary

We can use get() method or by key to access the elements in dictionary.

Example
 
 d = {1:"value","2":"Two"}
 
 #Accessing with key
 print("d[1]=",d[1])
 
 #Accessing using get() function
 print("d[2]=",d.get("2"))
Output ('d[1]=', 'value') ('d[2]=', 'Two')

Manipulate or add elements in dictionary

 my_info = {'name':'Rahul', 'age': 25}
 
 # update value
 my_info['age'] = 26
 
 #Output: {'age': 26, 'name': 'Rahul'}
 print(my_info)
 
 # add item
 my_info['address'] = 'India' 
 
 # Output: {'address': 'India', 'age': 26, 'name': 'Rahul'}
 print(my_info)

Delete elements from dictionary

There are various method to remove element from dictionary

pop() : This method removes the item from dictionary you just need to provide the key and it will return the item after removing.

popitem() : Returns an arbitrary item(key, value) from the dictionary after removing the item

Clear() : Removes all the items from dictionary.

Del : keyword can be used to remove items one by one

 
# create a dictionary
 cubes = {1:1, 2:8, 3:27, 4:64, 5:125} 
 
 # remove a particular item
 # Output: 64
 print(cubes.pop(4)) 
 
 # Output: {1:1, 2:8, 3:27, 4:64, 5:125}
 print(cubes)
 
 # remove an arbitrary item
 # Output: (1, 1)
 print(cubes.popitem())
 
 # Output: {2:8, 3:27, 4:64, 5:125}
 print(cubes)
 
 # delete a particular item
 del cubes[5] 
 
 # Output: {2: 8, 3: 27}
 print(cubes)
 
 # remove all items
 cubes.clear()
 
 # Output: {}
 print(cubes)
 
 # delete the dictionary itself
 del cubes
 
 # Throws Error
 # print(cubes)
Output
 
 64
 {1: 1, 2: 8, 3: 27, 5: 125}
 (1, 1)
 {2: 8, 3: 27, 5: 125}
 {2: 8, 3: 27}
 {}

Type casting or data type conversion

We can convert different data types into some other by using different type conversion functions like - int(), str(), float() , set() etc.

 > > > float("5.2")
 5.2
 > > > float(5.2)
 5.2

Note :When converting string to float it must be a compairtible float value Conversion from Float to Int will truncate the value after decimal

 >>> int(10.23)
 10
 >>> int(-11.96)
 -11
 >>>

We can even collections like list , set, dictionary, tuples

 >>> set([1,1,3,3,4,4,5,5,5,5])
 {1, 3, 4, 5}
 >>> tuple({1,2,5})
 (1, 2, 5)
 >>> list('hello')
 ['h', 'e', 'l', 'l', 'o']

Pairs are needed to convert to dictionary

 >>> dict([["key","value"],["key","value"]])
 {'key': 'value'}
 >>> dict([["key1","value1"],["key2","value2"]])
 {'key2': 'value2', 'key1': 'value1'}
 >>> dict([(3,27),(4,64)])
 {3: 27, 4: 64}
Summary
  • Python has flexible and powerful data structures with in-built functions for all basic manipulation

  • Accessing, retrieving and doing any computation is so easy with Python.

  • There is a lot more shorthand methods and especially dictionary and list are the most used data structures of Python they have many more speciality that you can learn.

Learn to Crack Your Technical Interview

Accept cookies & close this