0% found this document useful (0 votes)
2 views14 pages

Data Types With Examples

The document provides an overview of data types in Python, including numeric types (int, float, complex), string (str), boolean (bool), and collection types (list, tuple, dict, set). Each data type is explained with its characteristics, behaviors, and examples of how to use them in Python programming. It emphasizes the importance of these built-in data types for effective data manipulation and processing.

Uploaded by

myindiansun2024
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views14 pages

Data Types With Examples

The document provides an overview of data types in Python, including numeric types (int, float, complex), string (str), boolean (bool), and collection types (list, tuple, dict, set). Each data type is explained with its characteristics, behaviors, and examples of how to use them in Python programming. It emphasizes the importance of these built-in data types for effective data manipulation and processing.

Uploaded by

myindiansun2024
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Data types with Examples

Data types in Python refer to classifying or categorizing data objects based on their
characteristics and behavior. They define the type of values variables can hold and
determine the performed operations on those values. Python has several built-in data
types, including numeric types (int, float, complex), string (str), boolean (bool), and
collection types (list, tuple, dict, set). Each data type has its own set of properties,
methods, and behaviors that allow programmers to manipulate and process data
effectively in their programs.

Built-in Data Types in Python


Built-in data types in Python are fundamental data structures provided by the Python
programming language. They are pre-defined and available for use without requiring any
additional libraries or modules. Python offers several built-in data types, including:
1. Numeric Data Types: Numeric data types in Python are used to represent
numerical values. Python provides three primary numeric data types:
o Integer (int): Integers are whole numbers without any decimal points.
They can be positive or negative.
o Floating-Point (float): Floating-point numbers represent decimal values.
They can be positive or negative and may contain a decimal point.
o Complex (complex): Complex numbers are used to represent numbers
with a real and imaginary part. They are written in the form of a + bj,
where a is the real part and b is the imaginary part.
2. String Data Type(str): Represents a sequence of characters enclosed in single
quotes (‘ ‘) or double quotes (” “), such as “Hello, World!”, ‘Python’.
3. Boolean Data Type(bool): Represents either True or False, used for logical
operations and conditions.
4. Collection Data Types:
o list: Represents an ordered and mutable collection of items, enclosed in
square brackets ([]).
o tuple: Represents an ordered and immutable collection of items, enclosed
in parentheses ().
o dict: Represents a collection of key-value pairs enclosed in curly braces
({}) with unique keys.
o set: Represents an unordered and mutable collection of unique elements,
enclosed in curly braces ({}) or using the set() function.
Numeric Data Types
Numeric data types in Python are used to represent numerical values. Python provides
three primary numeric data types – integer (int), floating-Point (float) and complex
(complex). These numeric data types allow for performing various arithmetic operations,
such as addition, subtraction, multiplication, and division. They provide the necessary
flexibility to work with numerical data in Python programs.
 Int – It stores the integers values that can be positive or negative and do not
contain any decimal point. Example: num1=10, num2 = 15
 Float – These are floating-point real numbers that stores the decimal values. It
consists of integer and fraction parts. Example: fnum = 25.4, fnum1=67.8
 Complex – These are complex numbers specified as a real part and an imaginary
part. They are stored in the form of a + bj where a is the real part and j represents
the imaginary part. Example: num3= 2 + 3j, numcom = 5 – 7j
Python Code:

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
# Performing arithmetic operations
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
# Printing the results
print("Greater than:", greater_than)
print("Less than or equal to:", less_than_or_equal)
print("Equal to:", equal_to)
print("Not equal to:", not_equal_to)

Output:
Greater than: False
Less than or equal to: True
Equal to: False
Not equal to: True

Floating-Point Numbers (float)


The float data type in Python is used to represent floating-point numbers, which are
numbers with decimal points. Floats are used when more precision is needed than what
integers can provide. Floats are immutable like integers and follow the IEEE 754
standard for representing real numbers.
Example 1
# Assigning float values to variables
x = 3.14
y = 2.5
# Performing arithmetic operations
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.64
Difference: 0.64
Multiplication: 7.85
Division: 1.256

Example 2
# Using float values in comparisons
a = 1.2
b = 2.7
# Comparing the values
greater_than = a > b
less_than_or_equal = a <= b
equal_to = a == b
not_equal_to = a != b
# Printing the results
print("Greater than:", greater_than)
print("Less than or equal to:", less_than_or_equal)
print("Equal to:", equal_to)
print("Not equal to:", not_equal_to)

Output:
Greater than: False
Less than or equal to: True
Equal to: False
Not equal to: True

Complex Numbers (complex)


The complex data type in Python is used to represent numbers with both real and
imaginary parts. It is written in the form of a + bj, where a represents the real part and b
represents the imaginary part. Complex numbers are useful in mathematical calculations
and scientific computations that involve imaginary quantities.
Example 1
# Assigning complex values to variables
x = 2 + 3j
y = -1 + 2j
# Performing arithmetic operations
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: (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
# Comparing the values
equal_to = a == b
not_equal_to = a != b
# Printing the results
print("Equal to:", equal_to)
print("Not equal to:", not_equal_to)

Output:
Equal to: False
Not equal to: True

Textual Data Types – Strings


Textual data types in Python are used to represent and manipulate sequences of
characters, such as words, sentences, or even larger blocks of text. The primary textual
data type in Python is the string (str). Strings are enclosed in quotes (‘ ‘, ” “, or “”” “””)
and can be manipulated using various string methods. They are immutable, meaning their
values cannot be changed once assigned. String data types are commonly used for tasks
like text processing, input/output operations, and data manipulation.

Accessing String Values


Each character of a string can be expressed with the help of a technique called indexing.
In indexing, each character has an index value represented by either a positive or
negative integer starting from 0.
Syntax:- stringname[index]

Example
Str1=”Python
#accessing second character
Str1[1]
#accessing first four characters
Str1[0:4] # it will print the value from index 0 to 3
str1="Python"
>>> str1[1]
'y'
>>> str1[0:4]
'Pyth'
Positive indexing 0 1 2 3 4 5
String P y t h o n
-
Negative indexing -5 -4 -3 -2 -1
6
String Operations
1) Concatenation – Python allows us to join two different strings using the
concatenation operator ‘+’
Syntax:– str1 + str2
Example
>>> str1="Analytic"
>>> str2="Vidya"
>>> str3=str1 +str2
>>> print(str3)

2) Repetitions – Python allows us to repeat a given string with the help of ‘ * ‘ operator.
Syntax:– stringname * integervalue
Example
>>> str2 = "python"
>>> str2 * 3
'pythonpythonpython'

3) Membership – The Membership operator helps to check whether a given character is


present in the string or not with the help of two operators in and not in. In and not in
operator returns the boolean value True or False.
Syntax:– character in/not in stringname
Example
>>> str1="python"
>>> "p" in str1
True
>>> "f" in str1
False

Built-in Functions in String


1) Len() – It is used to calculate the length of the given string.
Syntax:– len(stringname)
Example
>>> str1="Python"
>>> len(str1)
6

2) isupper() – This function is used to check whether all the letters in a string are in the
upper case or not. If all the characters are in upper case then it returns True otherwise it
returns False.
Syntax:– [Link]()
Example
>>>str1= " Hello Everyone"
>>> [Link]()
False
>>> str2="HELLO"
>>> [Link]()
True

3) islower() – This function is used to check whether all the letters in a string are in
lowercase or not. If all the characters are in lower case then it returns True otherwise it
returns False.
Syntax:– [Link]()
Example
>>> s="hello"
>>> [Link]()
True
>>> s1="hey Folks!"
>>> [Link]()
False

4) upper() – It is used to convert all the characters of a string in uppercase.


Syntax:– [Link]()
Example
>>>str1= " Hello Everyone"
>>> [Link]()
' HELLO EVERYONE'

5) lower() – It is used to convert all the characters of a string in lowercase.


Syntax:– [Link] ()
Example
>>> str2="HELLO"
>>> [Link]()
'hello'

Boolean Data Type


The boolean data type in Python represents logical values of True and False. It is used to
evaluate conditions and make logical decisions in a program. Booleans are the result of
comparisons and logical operations.
Example 1
# Logical operations with booleans
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 :- [Link](element)
>>> list1=["apple","mango","grapes",123,345]
>>> [Link]("orange")
>>> list1
['apple', 'mango', 'grapes', 123, 345, 'orange']
>>> [Link]([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 :- [Link] (index,element)
>>> list2=["apple","mango","grapes",123,345]
>>> [Link](0,234)
>>> list2
[234, 'apple', 'mango', 'grapes', 123, 345]
>>> [Link](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:– [Link](element)
>>> list3=[12,45,12,67,78,90]
>>> [Link](12)
2
>>> [Link](11)
0

4) reverse() – reverse function is used to reverse the order of elements in the list.
Syntax:– [Link]()
>>> list3=[12,45,12,67,78,90]
>>> [Link]()
>>> 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:– [Link]()
list4=["grapes","banana","apple","mango"]
>>> [Link]()
>>> list4
['apple', 'banana', 'grapes', 'mango']
>>>list5=[12,45,12,67,78,90]
>>>[Link]()
[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:- [Link]()
>>> dict1={"comp": "computer" , "sci" : "science","comm":"commerce"}
>>> [Link]()
dict_items([('comp', 'computer'), ('sci', 'science'), ('comm', 'commerce')])

2) keys() – This function returns the list of keys in the dictionary.


Syntax:- [Link]()
>>> dict1={"comp": "computer" , "sci" : "science","comm":"commerce"}
>>> [Link]()
dict_keys(['comp', 'sci', 'comm'])

3) values() – It returns the list of values in the dictionary.


Syntax:- [Link]()
>>> dict1={"comp": "computer" , "sci" : "science","comm":"commerce"}
>>> [Link]()
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:- [Link](dictionary2)
>>> dict1={"comp": "computer" , "sci" : "science","comm":"commerce"}
>>> dict2={"acc":"accounts","bst":"business studies"}
>>> [Link](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
for element in my_set:
print(element)
# Checking membership
is_present = 3 in my_set
# Printing the results
print(my_set)
print(is_present)
Output:
1
2
3
4
5
{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 = [Link](set2)
# Intersection of sets
intersection = [Link](set2)
# Difference of sets
difference = [Link](set2)
# Printing the results
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)
# Accessing elements by index
first_element = my_tuple[0]
last_element = my_tuple[-1]
# Slicing a tuple
subset = my_tuple[1:4]
# Printing the results
print(my_tuple)
print(first_element)
print(last_element)
print(subset)
Output:
(1, 2, 3, 4, 5)

1
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
[Link] 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:
def __init__(self, x, y):
self.x = x
self.y = y
# Creating objects
point1 = Point(2, 3)
point2 = Point(5, 7)
# Accessing object attributes
print(point1.x, point1.y)
print(point2.x, point2.y)

Output:
23
57

Example 2: Adding methods to a class


# Defining a class with methods
class Circle:
def __init__(self, radius):
[Link] = radius
def area(self):
return 3.14 * [Link] ** 2
# Creating an object and using methods
circle = Circle(5)
print([Link]())

Output:
78.5

You might also like