Thanks to theidioms.com

Learn Python for Data Science (Course I)

Learn Python for Data Science (Course I)

Data Types and Operations in Python

In this chapter, you will learn about data types and operations in Python.

A data type specifies the type of value that a variable has and the type of operations that can be applied to the 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:

Data TypeExample
str‘Apple’, ‘Ball’
int123, 66, 222
float2.4, 3.21, 4.666
list[‘Python’, ‘C’, ‘C++’], [‘Nepal’, ‘USA’]
tuple(‘Python’, ‘C’, ‘C++’), (‘Nepal’, ‘USA’)
set{‘a’, ‘b’, ‘c’}, {1,2,3,4}
dict{‘Name’:’John’}, {‘id’:1, ‘age’: 48}
boolTrue, False

You can also use the in-built type() function in Python to get the data type of an object.

# Example of using the type() function

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

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

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

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

Now, let us move onto discuss the characteristics of some commonly used Python data types.

1. Strings (str)

Variables of type String are surrounded by either single or double quotation marks. For example,

# Both variable1 and variable2 are strings

>>> variable1 = "Python" 
>>> variable2 = 'Python'

The examples demonstrated below showcase results from different types of string operations performed 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. Integers (int) and Floats (float)

Integers are numbers without a decimal point. 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. Lists (list)

Lists are array sequences that store a collection of items of the same or different data types. The elements of a list are surrounded by square brackets [ ] and the item indexing starts at 0. This means that the first item of a list has an index of 0, the second item of a list has an index of 1, and so on.

# variable1 is a list of integers
>>> variable1 = [1, 2, 3, 4, 5]

# variable2 is a list 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. Tuples (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. 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. Sets (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'}

This chapter concludes the basics of data types and operations in Python. In the next chapter, we will discuss the various Control Flow Tools in Python.

Leave your thought here

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

Close Bitnami banner
Bitnami