Thanks to theidioms.com

Data Types and Operations in Python

Python Programming for Newbies
Python Programming for Newbies

Data Types and Operations in Python


Learn the different data types and operations available in Python in this in-depth lesson.

Having the knowledge of data types and operations in Python helps you to identify what type of value a variable has and what operations can be applied to that variable.


Basic Data Types in Python

Python contains several data types to make it easier for programmers to write functional and replicable programs. The different data types used in Python are listed below:

NameData TypeExample
Python Stringstr‘Apple’, ‘Ball’
Python Integerint123, 66, 222
Python Floatfloat2.4, 3.21, 4.666
Python Listlist[‘Python’, ‘C’, ‘C++’], [‘Nepal’, ‘USA’]
Python Tupletuple(‘Python’, ‘C’, ‘C++’), (‘Nepal’, ‘USA’)
Python Dictionarydict{‘Name’:’John’}, {‘id’:1, ‘age’: 48}
Python Setset{‘a’, ‘b’, ‘c’}, {1,2,3,4}
Python BooleanboolTrue, False

Now, let us move onto discuss the characteristics of all of these data types one-by-one.


1. Python String (str)

A string is a sequence of characters and they are surrounded by either single or double quotation marks. For example,

# A string made using single quotation marks
variable1 = "Python" 

# A string made using double quotation marks
variable2 = 'Python'

There are multiple operations that can be performed on strings in Python:

# Adding two strings together results in string concatenation
>>> 'apple' + 'banana'
'applebanana'

# Multiplying a string by a number results in multiple concatenations of the same string
>>> 'apple' * 3
'appleappleapple'

#  Finding the length of the string using the in-built len() function
>>> len("apple")
5

2. Python Integer (int) and Python Float (float)

Integers are numbers without a decimal point whereas floats (or floating-point numbers) are numbers with a decimal point. For example, the number 100 is an integer and the number 100.0 is a floating-point number.

# variable1 is an integer
>>> variable1 = 1

# variable2 is a float
>>> variable2 = 1.0

The following examples showcase results of different arithmetic operations performed using integers and floats:

# Addition/subtraction of integers returns an integer
>>> 2 + 2    
4 

# Addition/subtraction of an integer and a float returns a floating point number
>>> 2 + 2.0
4.0 

# Division always returns a floating-point number
>>> 10 / 2
5.0 

# A floating-point number is accurate up to 15 decimal places
>>> 17 / 3  
5.666666666666667 

# Floor division discards the fractional part and return an integer
>>> 17 // 3  
5

# The % operator returns the remainder of the division
>>> 17 % 3  
2

# The ** operator returns x to the power of y. 
>>> 5 ** 2 # 5 to the power of 2
25

# Multiplication of variables
>>> width = 20
>>> height = 5 * 9
>>> width * height
900

# Use of different arithmetic operations may return an integer or a floating-point number
>>> 50 - 5*6    
20 

>>> (50 - 5*6) / 4  
5.0 

3. Python List (list)

Lists are array sequences that store a collection of items of the same or different data types.

In a list, the elements are surrounded by square brackets [ ] and the indexing of these elements starts at 0. This means that the first item has an index of 0, the second item has an index of 1, and so on.

# variable1 storing integers
>>> variable1 = [1, 2, 3, 4, 5]

# variable2 storing different data types
>>> variable2 = [1.0, 2, 3, 4.0, '5']

The following examples showcase results of different types of list operations:

# squares is a list of integers
>>> squares = [1, 4, 9, 16, 25] 
>>> squares
[1, 4, 9, 16, 25] 

# Finding the length of the list using the in-built len() function
>>> len(squares) # gives length of list
5

# Accessing the items of a list based on the index of the item
>>> squares[0]  # 0 index fetches the first item
1
>>> squares[-1] # -1 index fetches the last item
25
>>> squares[-2] # -2 index fetches the second last item
16

# Slicing the list to get a selection of items 
>>> squares[1:]  # Fetching all elements starting from index 1
[4, 9, 16, 25]
>>> squares[2:]  # Fetching all elements starting from index 2
[9, 16, 25]
>>> squares[:1]  # Fetching all elements till and not including index 1
[1]
>>> squares[:2]  # Fetching all elements till and not including index 2
[1, 4]
>>> squares[:-2]  # Fetching all elements except the last two elements
[1, 4, 9]
>>> squares[1:3]  # Fetching all elements from index 1 to index 3
[4, 9]
>>> squares[:]  # Fetching all elements of the list
 [1, 4, 9, 16, 25] 

# Replacing an element of a list
>>> squares[3] = 12  # Assigning item at index 3 as 12
>>> squares
[1, 4, 9, 12, 25]
 
# Remove a range of values of the list
>>> squares[1:3] = [ ]  # Removing items at index 1 to 3
>>> squares
[1, 12, 25]

# Clear the list by replacing all the elements with an empty list
>>> squares[:] = [ ] 
>>> squares
[ ]


4. Python Tuple (tuple)

Tuples are array sequences that store a collection of items of the same or different data types. The elements of a tuple are surrounded by round brackets, that is, ( ). Tuples are like lists, except for the fact that the elements of a tuple cannot be changed after initialization.

# variable1 is a tuple of integers
>>> variable1 = (1, 2, 3, 4, 5)

# variable2 is a tuple storing different data types
>>> variable2 = (1.0, 2, 3, 4.0, '5')

The following examples showcase results of different types of tuple operations:

# Defining a tuple with integer values
>>> squares = (1, 4, 9, 16, 25) 
>>> squares
(1, 4, 9, 16, 25)               

# Finding the length of the tuple using the in-built len() function
>>> len(squares) # gives length of tuple 
5

# Accessing the items of a tuple based on the index of the item
>>> squares[0]  # 0 index fetches the first item
1
>>> squares[-1] # -1 index fetches the last item
25
>>> squares[-2] # -2 index fetches the second last item
16

# Slicing the tuple to get a selection of items 
>>> squares[1:]  # Fetching all elements starting from index 1
(4, 9, 16, 25)
>>> squares[2:]  # Fetching all elements starting from index 2
(9, 16, 25)
>>> squares[:1]  # Fetching all elements till and not including index 1
(1)
>>> squares[:2]  # Fetching all elements till and not including index 2
(1, 4)
>>> squares[:-2]  # Fetching all elements except the last two elements
(1, 4, 9)
>>> squares[1:3]  # Fetching all elements from index 1 to index 3
(4, 9)
>>> squares[:]  # Fetching all elements of a tuple 
 (1, 4, 9, 16, 25)

# Unlike lists, the elements of a tuple cannot be changed.
>>> squares[3] = 12
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

5. Python Dictionary (dict)

A dictionary is a set of key-value pairs. Every key in a dictionary must be unique. The elements of a dictionary are surrounded by curly brackets, i.e., { }.

# variable1 is a dictionary
>>> variable1 = {'key1' : 'value1', 'key2' : 'value2'}

The following examples demonstrate results of different types of dictionary operations:

# Defining a dictionary
>>> costs_dict = {'Kitkat':1300, 'Unicorn':1800, 'Chocolateroll':1000, 'Barbiedoll':3600, 'MickeyMouse':3600, 'Doraemon':1800} 
>>> costs_dict
{'Kitkat': 1300, 'Unicorn': 1800, 'Chocolateroll': 1000, 'Barbiedoll': 3600, 'MickeyMouse': 3600, 'Doraemon': 1800}

# Printing value from given key
>>> cost_doraemon_cake = costs_dict['Doraemon'] 
>>> cost_doraemon_cake 
1800

# Inserting new key value pair
>>> costs_dict['PeppaPig '] = 1800
>>> costs_dict
{'Kitkat': 1300, 'Unicorn': 1800, 'Chocolateroll': 1000, 'Barbiedoll': 3600, 'MickeyMouse': 3600, 'Doraemon': 1800, 'PeppaPig ': 1800}

# Removing key value pair
>>> del costs_dict['Doraemon']
>>> costs_dict
{'Kitkat': 1300, 'Unicorn': 1800, 'Chocolateroll': 1000, 'Barbiedoll': 3600, 'MickeyMouse': 3600, 'PeppaPig ': 1800}

# Replacing the value for a given key
>>> costs_dict['Unicorn'] = 3800
>>> costs_dict
{'Kitkat': 1300, 'Unicorn': 3800, 'Chocolateroll': 1000, 'Barbiedoll': 3600, 'MickeyMouse': 3600, 'Doraemon': 1800, 'PeppaPig ': 1800}

# Convert the key to list
>>> cake_items = list(costs_dict)
>>> cake_items
['Kitkat', 'Unicorn', 'Chocolateroll', 'Barbiedoll', 'MickeyMouse', 'PeppaPig ']

6. Python Set (set)

A set is an unordered collection of non-duplicated elements. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference. The elements of a set are surrounded by curly brackets, that is, { } but they do not exist as key-value pairs like in a dictionary.

# variable1 is a set
>>> variable1 = {1, 2, 3, 4, 5}

The following examples demonstrate results of different types of set operations:

# Defining a set
>>> cake_items = {'Kitkat', 'Unicorn', 'Chocolateroll', 'Barbiedoll', 'MickeyMouse', 'Doraemon'}
>>> cake_items
{'Chocolateroll', 'MickeyMouse', 'Kitkat', 'Doraemon', 'Unicorn', 'Barbiedoll'}

# Fast membership testing
>>> 'Doraemon' in cake_items
True
>>> 'Ogge' in cake_items
False

# Creating a set called 'A' from a string using the in-built set() function
>>> A = set('aezakmi')
>>> A
{'k', 'm', 'z', 'e', 'i', 'a'}

# Creating a set called 'B' from a string using the in-built set() function
>>> B = set('alacazam')
>>> B
{'l', 'm', 'z', 'c', 'a'}

# Letters in A but not in B
>>> print("A-B:", A-B)
A-B: {'k', 'i', 'e'}

# Letters in A or B or both
>>> print("A|B:", A|B)
A|B: {'k', 'l', 'm', 'e', 'z', 'c', 'i', 'a'}

# Letters in both A and B
>>> print("A&B:", A&B)
A&B: {'a', 'z', 'm'}

# Letters in A or B but not both
>>> print("A^B:", A^B)
A^B: {'k', 'l', 'c', 'e', 'i'}

7. Python Boolean (bool)

A Python Boolean represents either the value ‘True’ or ‘False’.

# variable1 is a boolean
>>> variable1 = True

# variable2 is a boolean
>>> variable2 = False

Booleans are mostly generated when evaluating expressions such as:

# Is 10 greater than 4?
>>> 10 > 4
True

# Is 10 less than 4?
>>> 10 < 4
False

# Does 10 equals 10?
>>> 10 == 10
False

# Does 10 equals 4?
>>> 10 == 4
False

Use Python type() function to check data type

Here’s a tip — if you ever get confused about what data type a value is, just use the type() function.

We’ll teach you what functions are later in this course but for now, you can use the type() function by passing in a single value within the round brackets in the following way:

# Example of using the type() function

>>> type("Apple")
<class 'str'>

>>> type(2)
<class 'int'>

>>> type(2.4)
<class 'float'>

>>> type({'asd','ert'})
<class 'set'>

You can see that all of the outputs have the general format <class data_type>. This is because data types in Python are stored in the format of a class (we will talk about this later on in this course as well).


This chapter concludes with the basics of data types and operations in Python.

Leave your thought here

Your email address will not be published. Required fields are marked *