Built in Datatypes
Built in Datatypes
Built in Datatypes
Integers (int)
Python’s integer data type (int) represents whole numbers
without any decimal points. It stores positive and negative
whole numbers. Integers are immutable, meaning their value
cannot be changed once assigned.
Example 1
# Assigning integer values to variables
x=5
y = -10
sum_result = x + y
difference_result = x - y
multiplication_result = x * y
division_result = x / y
# Printing the results
print("Sum:", sum_result)
print("Difference:", difference_result)
print("Multiplication:", multiplication_result)
print("Division:", division_result)
Output:
Sum: -5
Difference: 15
Multiplication: -50
Division: -0.5
Example 2
# Using integer values in comparisons
a = 10
b = 20
# Comparing the values
greater_than = a > b
less_than_or_equal = a <= b
equal_to = a == b
not_equal_to = a != b
x = 3.14
y = 2.5
sum_result = x + y
difference_result = x - y
multiplication_result = x * y
division_result = x / y
print("Sum:", sum_result)
print("Difference:", difference_result)
print("Multiplication:", multiplication_result)
print("Division:", division_result)
Output:
Sum: 5.64
Difference: 0.64
Multiplication: 7.85
Division: 1.256
Example 2
# Using float values in comparisons
a = 1.2
b = 2.7
greater_than = a > b
less_than_or_equal = a <= b
equal_to = a == b
not_equal_to = a != b
x = 2 + 3j
y = -1 + 2j
difference_result = x - y
multiplication_result = x * y
division_result = x / y
print("Sum:", sum_result)
print("Difference:", difference_result)
print("Multiplication:", multiplication_result)
print("Division:", division_result)
Output:
Sum: (1+5j)
Difference: (3+1j)
Multiplication: (-8+1j)
Division: (0.8-1.4j)
Example 2
# Using complex values in comparisons
a = 1 + 2j
b = 3 + 4j
equal_to = a == b
not_equal_to = a != b
a = True
b = False
result_and = a and b
result_or = a or b
result_not = not a
print(result_and)
print(result_or)
print(result_not)
Output:
False
True
False
Example 2
# Comparisons using booleans
x=5
y = 10
greater_than = x > y
less_than_or_equal = x <= y
equal_to = x == y
not_equal_to = x != y
print(greater_than)
print(less_than_or_equal)
print(equal_to)
print(not_equal_to)
Output:
False
True
False
True
Collection Data Types
Collection data types in Python are used to store and organize
multiple values into a single entity. Python provides several
built-in collection data types, including lists, tuples,
dictionaries, and sets.
Lists (list)
The list data type in Python is used to store multiple items in a
single variable. Lists are ordered, mutable, and can contain
elements of different data types. They are created by
enclosing comma-separated values within square brackets [ ].
Example 1
List1=[123,567,89] #list of numbers
List2=[“hello”,”how”,”are”] #list of strings
List3= [“hey”,1223,”hello”] #list of mixed data type.
Accessing Elements of the List
Elements of the list are accessed in the same as that of string
that is with the help of positive and negative indexing. Slicing
is also used to access the list elements in which more than a
single element is accessed at a time.
List1=[“apple”,123,”mango”,[2,3,4,]]
Positive index 0 1 2 3
List “apple” 123 “mango” [2,3,4]
Negative
-4 -3 -2 -1
index
Example
>>> list1=['apple',123,"mango",[2,3,4,]]
>>> list1[0]
'apple'
>>> list1[3]
[2, 3, 4]
>>> list1[1:3]
[123, 'mango']
Operations in List
1) Concatenation – Two lists are concatenated with the help
of “+” operator.
Syntax:- list1 + list2
>>> list1=["apple","mango",123,345]
>>> list2 = ["grapes"]
>>> list1 + list2
['apple', 'mango', 123, 345, 'grapes']
2) Repititions – With the help of the ‘ * ‘ operator list can be
repeated n number of times.
Syntax:- list1* number
>>> list1=["apple","mango",123,345]
>>> list1*2
['apple', 'mango', 123, 345, 'apple', 'mango', 123, 345]
3) Membership – ‘ in ‘and ‘ not in ‘ are two membership
operators that are used to check whether the given element is
present in the list or not and return a Boolean value True or
False.
Syntax:– element in/not in in list1
>>> list1=["apple","mango",123,345]
>>> 'apple' in list1
True
>>> 'apple' not in list1
False
Built-in functions in the list
1) append() – This function is used to add a single element at
the end of the list. The single element that is added can be of
any data type like integer, list, string, etc.
Syntax :- listname.append(element)
>>> list1=["apple","mango","grapes",123,345]
>>> list1.append("orange")
>>> list1
['apple', 'mango', 'grapes', 123, 345, 'orange']
>>> list1.append([12,34,55])
>>> list1
['apple', 'mango', 'grapes', 123, 345, 'orange', [12, 34, 55]]
2) insert() – insert() function is also used to add element in
this list but with the help of insert we can add the element at a
particular index in the list. If the index is not present then it
will add the element at the end of the list.
Syntax :- listname.insert (index,element)
>>> list2=["apple","mango","grapes",123,345]
>>> list2.insert(0,234)
>>> list2
[234, 'apple', 'mango', 'grapes', 123, 345]
>>> list2.insert(6,"papapa")
>>> list2
[234, 'apple', 'mango', 'grapes', 123, 345, 'papapa']
3) count() – count function is used to count the number of
time an element occurs in the list.
Syntax:– listname.count(element)
>>> list3=[12,45,12,67,78,90]
>>> list3.count(12)
2
>>> list3.count(11)
0
4) reverse() – reverse function is used to reverse the order of
elements in the list.
Syntax:– listname.reverse()
>>> list3=[12,45,12,67,78,90]
>>> list3.reverse()
>>> list3
[90, 78, 67, 12, 45, 12]
5) sort() – sort function is used to arrange the elements of the
list in ascending order. The function list must contain all the
elements in the same data type that is either integers or
strings.
Syntax:– listname.sort()
list4=["grapes","banana","apple","mango"]
>>> list4.sort()
>>> list4
['apple', 'banana', 'grapes', 'mango']
>>>list5=[12,45,12,67,78,90]
>>>list5.sort()
[12,12,45,67,78,90]
Dictionary
Dictionary is a special data type that is a mapping between a
set of keys and a set of values. It represents a key-value pair
enclosed in curly brackets and each element is separated by a
comma. Key-value pairs are separated by the colon. The
elements of the dictionaries are unordered and the key is
unique for each value in the dictionary. The elements of the
dictionary are mutable that is its elements can be changed
once it is created.
Syntax:- Dictionaryname={key:value}
Example
Dict1={“comp”: “computer” , “sci” : “science”}
Dict2={“123”:”computer”,456 : “maths”}
Accessing Elements of the Dictionary
The elements of the dictionary are accessed with the help of
the keys. Each key serves as an index and maps the value in
the dictionary.
Syntax:- dictionaryname[key]
>>> dict1={"comp": "computer" , "sci" : "science"}
>>> dict1["comp"]
'computer'
>>> dict1["sci"]
'science'
New elements are added in the dictionary with the help of a
new key.
>>> dict1={"comp": "computer" , "sci" : "science"}
>>> dict1["comm"]="commerce"
>>> dict1
{'comp': 'computer', 'sci': 'science', 'comm': 'commerce'}
Built-in Functions in the Dictionary
1) items() – items() function returns a list of tuples of key-
value pair of the dictionary.
Syntax:- dictionaryname.items()
>>> dict1={"comp": "computer" , "sci" :
"science","comm":"commerce"}
>>> dict1.items()
dict_items([('comp', 'computer'), ('sci', 'science'), ('comm',
'commerce')])
2) keys() – This function returns the list of keys in the
dictionary.
Syntax:- dictionaryname.keys()
>>> dict1={"comp": "computer" , "sci" :
"science","comm":"commerce"}
>>> dict1.keys()
dict_keys(['comp', 'sci', 'comm'])
3) values() – It returns the list of values in the dictionary.
Syntax:- dictionaryname.values()
>>> dict1={"comp": "computer" , "sci" :
"science","comm":"commerce"}
>>> dict1.values()
dict_values(['computer', 'science', 'commerce'])
4) len() – length function is used to count the total number of
elements in the dictionary.
Syntax:- len(dictionaryname)
>>> dict1={"comp": "computer" , "sci" :
"science","comm":"commerce"}
>>> len(dict1)
3
5) update() –it is used to append the key-value pair of the
dictionary passed as the argument to the key-value pair of the
given dictionary.
Syntax:- dictionary1.update(dictionary2)
>>> dict1={"comp": "computer" , "sci" :
"science","comm":"commerce"}
>>> dict2={"acc":"accounts","bst":"business studies"}
>>> dict1.update(dict2)
>>> dict1
{'comp': 'computer', 'sci': 'science', 'comm': 'commerce', 'acc':
'accounts', 'bst': 'business studies'}
Sets (set)
The set data type in Python is an unordered collection of
unique elements. It is used to store multiple items without any
duplicates. Sets are created by enclosing comma-separated
elements within curly braces { } or by using the set()
constructor.
Example: Set creation and accessing elements
# Creating a set
my_set = {1, 2, 3, 4, 5}
# Accessing elements
print(element)
# Checking membership
is_present = 3 in my_set
# Printing the results
print(my_set)
print(is_present)
Output:
1
{1, 2, 3, 4, 5}
True
Example 2: Set operations
# Set operations
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# Union of sets
union = set1.union(set2)
# Intersection of sets
intersection = set1.intersection(set2)
# Difference of sets
difference = set1.difference(set2)
print(union)
print(intersection)
print(difference)
Output:
Copy code
{1, 2, 3, 4, 5, 6, 7, 8}
{4, 5}
{1, 2, 3}
Tuples (tuple)
The tuple data type in Python is similar to a list but with one
crucial difference: tuples are immutable. Once created, the
elements in a tuple cannot be modified. Tuples are created by
enclosing comma-separated values within parentheses ( ).
Example: Tuple creation and accessing elements
# Creating a tuple
my_tuple = (1, 2, 3, 4, 5)
first_element = my_tuple[0]
last_element = my_tuple[-1]
# Slicing a tuple
subset = my_tuple[1:4]
print(my_tuple)
print(first_element)
print(last_element)
print(subset)
Output:
(1, 2, 3, 4, 5)
(2, 3, 4)
Custom Data Types in Classes
In Python, classes provide a way to define custom data types.
Classes encapsulate data and methods, allowing for the
creation of objects with specific attributes and
behaviors.Classes serve as blueprints for creating objects.
They define the structure and behavior of objects, including
their attributes (data) and methods (functions). Objects are
instances of classes, and each object has its own unique state
and behavior.
Example: Creating a class and instantiating objects
# Defining a class
class Point:
self.x = x
self.y = y
# Creating objects
point1 = Point(2, 3)
point2 = Point(5, 7)
print(point2.x, point2.y)
Output:
23
57
Example 2: Adding methods to a class
# Defining a class with methods
class Circle:
self.radius = radius
def area(self):
print(circle.area())
Output:
78.5
Conclusion
Python data types form the foundation of any Python
programming endeavor. Understanding and utilizing these
data types effectively is essential for developing robust and
efficient applications. By mastering the intricacies of Python
data types, you will have the necessary skills to tackle
complex programming challenges.
Numeric Functions
A numeric object of one type can be converted in another
type using the following functions: