Data Types in Python

In this tutorial, I am going to discuss about different Data Types provided in Python and how to use them.

Data Types in Python

As we know python is an object oriented language that's why all the data types in python are basically objects. In other words, data in python takes the form of objects - either built-in object provided by python or objects created by users externally.

But how do objects fit in the python programs ?

Programs consists of modules which perform different functions. These modules contain statements which collectively perform functions of the modules. Statements in a module contain expressions. These expressions create and process objects.

The data used in a program and stored in a memory can be of many types. Like, Someone's age can be stored as a numeric value, their address can be stored as an alphanumeric value.

Python provides various standard data types which have operations that can be performed on them.

Following are the basic data types in python:

  • Boolean
  • Number
  • String
  • List
  • Tuple
  • Set
  • Dictionary

Python also provides a function type() using which we can know which a class a variable or value belongs to. There is also an isinstance() function which checks if a variable or value belongs to a class.

Boolean

It is the most basic type in programming. A boolean variable represents two values either True or False.

bool1 = True
print("True ", "is of type : " ,type(bool1))
bool2 = bool(20)
print("bool(20) ", "is of type : ", type(bool2))
True  is of type :  
bool(20)  is of type :  

Numbers

Integers, Floating-point numbers (numbers with decimal point in them) and complex numbers (numbers of the form X+Yj) fall under Numbers Data type in python.

a = 1
print(a," is of type : ", type(a))
b = 3.2
print(b," is of type : ", type(b))
c = 1+6j
print(c," is a complex number ? ",isinstance(c,complex))
1  is of type :  
3.2  is of type :  
(1+6j)  is a complex number ?  True

Integers can be of any length in python, it is only limited by memory availability.

A floating-point number is accurate up to 15 decimal places. Integer and Floating-points are separated by decimal points. 2 is an integer and 2.0 is a floating-point number.

Complex numbers are written in the form, x + yj, where x is the real part and y is the imaginary part.

Here are some examples :

val1 = 123456789012345678901234567890
print("val1 = ", val1)
#Notice that float variable val2 is truncated.
val2 = 0.1234567890123456789
print("val2 = ", val2)  
complex_num = 3+8j
print("complex_num = ",complex_num)
val1 =  123456789012345678901234567890
val2 =  0.12345678901234568
complex_num =  (3+8j)

String

String is an ordered collection of characters which are used to store and represent text-based information.

In python strings can be used to represent almost anything which can be encoded as text : symbols and words (e.g your name), contents of text file etc. In python strings are represented as objects of class 'str'.

Strings can be represented using single quotes (' ') or double quotes (" "). Multi-line strings can be represented using """ or '''.

str1 = 'Hello'
str2 = "Welcome"
str3 = '''To 
Learn'''
str4 = """ Python 
programming"""

print(str1,str2,str3,str4)
Hello Welcome To 
Learn  Python 
programming

Indexing starts from 0 in python i.e first character of a string is at 0th position and then the position increments by 1 for each character.

We can use slicing operator ( [] ) to extract characters from a string.

However strings are immutable in python which means value of characters in strings cannot be altered.

new_str = 'Welcome to Learn Python'
print("new_str[5] = ",new_str[5])  #new_str[5] = m
print("new_str[8:14] = ",new_str[8:14])
#Generates error as strings are immutable in python.
new_str[2] = 'k' 
new_str[5] =  m
new_str[8:14] =  to Lea

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

 in 
      3 print("new_str[8:14] = ",new_str[8:14])
      4 #Generates error as strings are immutable in python.
----> 5 new_str[2] = 'k'

TypeError: 'str' object does not support item assignment

List

Lists are the most versatile ordered collection data types of python. List is one of the most used data-types of python as it offers so much flexibility and is easy to use.

All the elements of a list need not be of a same type.

In python, a list is declared using square brackets [ ] enclosing elements of the list separated by comma.

x = [2, 4, 'learn', 3.0]

The slicing operator [ ] is used to extract an element or a range of elements from a list.

list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
print("list1[4] = ",list1[4])
print("list1[0:5]",list1[0:5])
print("list1[8:]",list1[8:])
print("list1[:6]",list1[:6])
list1[4] =  5
list1[0:5] [1, 2, 3, 4, 5]
list1[8:] [9, 10, 11, 12, 13, 14, 15]
list1[:6] [1, 2, 3, 4, 5, 6]

Lists in python are mutable which means that elements of a list can be altered.

list2 = [1, 2, 3, 4, 5]
print("before change list2 = ",list2)
list2[3] = 27
print("after change list2 = ",list2)
before change list2 =  [1, 2, 3, 4, 5]
after change list2 =  [1, 2, 3, 27, 5]

Tuple

Tuple is another sequence data type in python which is very similar to list.

The main difference between tuple and list is that list is enclosed within brackets [ ] and their elements and size can be changed whereas a tuple is enclosed within parentheses ( ) and cannot be updated i.e. tuples are immutable.

Once created tuples cannot be modified. They are generally used to write-protect data as they cannot be changed dynamically.

Tuples are defined within parentheses ( ) and elements are separated by commas.

t = (5, 'python', 4.21)

For accessing elements of a tuple slicing operator is used similarly as used for lists or strings.

t = (1, 2, 4, "programming", 'language')
print("t[2] = ",t[2])
print("t[0:4] = ",t[0:4])
#Generates error as tuples are immutable in python
t[1] = 3
t[2] =  4
t[0:4] =  (1, 2, 4, 'programming')

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

 in 
      3 print("t[0:4] = ",t[0:4])
      4 #Generates error as tuples are immutable in python
----> 5 t[1] = 3

TypeError: 'tuple' object does not support item assignment

Set

A set is an unordered collection of elements. Every set elements is unique and must be immutable(cannot be changed).

However set itself is mutable i.e. we can add or remove elements from a set.

Set in python is defined as values separated by comma enclosed within braces { }.

set1 = {1, 2, 3, 4, 5}
print("set1 = ",set1)
print(type(set1))
set1 =  {1, 2, 3, 4, 5}

In python, set operations like union, intersection can also be performed on two sets. Sets always have unique values, if a set have duplicate values then they are eliminated as it is.

set2 = {1, 2, 4, 4, 4, 5, 6, 6}
print("set2 = ",set2)
set2 =  {1, 2, 4, 5, 6}

As set is an unordered collection indexing has no meaning, thus slicing operator [ ] does not work for sets.

print("set2 = ",set2)
print("set2[3]",set2[3])
set2 =  {1, 2, 4, 5, 6}

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

 in 
      1 print("set2 = ",set2)
----> 2 print("set2[3]",set2[3])

TypeError: 'set' object is not subscriptable

Dictionary

A dictionary in python is an unordered collection of key-value pairs.

Dictionaries are defined with braces ( { } ) with each item in the form of key:value pair separated by comma. Values can be assigned and accessed by using square braces ( [ ] ).

Key and value can be of any data type.

dict1 = { 1:'value1', 2:'value2'}
print(type(dict1))

In a dictionary, a key is used to retrieve the respective value. But the opposite is not possible.

dict2 = { 'one':1, 'two':2 }
print(type(dict2))
print("dict2['one'] = ",dict2['one'])
print("dict2['two'] = ",dict2['two'])

#Generates error because value cannot be used to access a key
print("dict2[2] = ",dict2[2])

dict2['one'] =  1
dict2['two'] =  2

---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

 in 
      5 
      6 #Generates error because value cannot be used to access a key
----> 7 print("dict2[2] = ",dict2[2])

KeyError: 2

Conversion between Data Types

Conversion between different data types is possible using different type conversion functions like int(), float(), str() etc.

Let's see how to use these functions :

print("Conversion of integer to float : ")
print(float(8))

print("\nConversion of float to integer : ")
print(int(10.368))
print(int(-10.234))
Conversion of integer to float : 
8.0

Conversion of float to integer : 
10
-10

Notice that when we convert float to int, the decimal value is truncated.

To convert integer/float values to and from string must contain correct compatible values.

print("string to float : ",float('13.45'))
print("string to integer : ",int('56'))
print("float to string : ",str(34.257))
print("integer to string : ",str(23))

#Incomatible value 
print(int('24v'))
string to float :  13.45
string to integer :  56
float to string :  34.257
integer to string :  23

---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

 in 
      4 print("integer to string : ",str(23))
      5 
----> 6 print(int('24v'))

ValueError: invalid literal for int() with base 10: '24v'

Notice that when we give an incompatible value such as '34v' to int() function it gives us a ValueError.

It is also possible to convert one sequence to another:

print(set([4,6,8]))
print(tuple({1,2,3}))
print(list('convert'))
print(tuple('tuple'))
{8, 4, 6}
(1, 2, 3)
['c', 'o', 'n', 'v', 'e', 'r', 't']
('t', 'u', 'p', 'l', 'e')

To convert to a dictionary, each element should be in pair :

list1 = [[1,2],[3,4]]
tuple1 = (('key',1),('value',2))
print(dict(list1))
print(dict(tuple1))
{1: 2, 3: 4}
{'key': 1, 'value': 2}

Conclusion

In this tutorial, we have discussed basics about different datatypes available in python like numbers, strings, boolean, list, tuple, set and dictionary.

We have also discussed about conversion of one datatype to another. We are going to discuss about each of these datatypes in detail in further articles.

If you have any questions please comment below also share your views and suggestions in the comment box.

Pooja is a programmer by profession and love to write articles on Python. She is highly interested in Python, Data Science and Machine Learning. Pooja holds B.E. Computer Engineering degree. She loves teaching and learning new thing.

Leave a Comment