PSPP Unit-2 Notes
PSPP Unit-2 Notes
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
Python Numbers
There are three numeric types in Python:
int
float
complex
Variables of numeric types are created when you assign a value to them:
To verify the type of any object in Python, use the type() function:
Example
print(type(x))
print(type(y))
print(type(z))
Int
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
Example
Integers:
x = 1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
Float
Float, or "floating point number" is a number, positive or negative, containing one or more decimals.
Example
Floats:
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
Float can also be scientific numbers with an "e" to indicate the power of 10.
Example
Floats:
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Complex
Complex numbers are written with a "j" as the imaginary part:
Example
Complex:
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
Type Conversion
You can convert from one type to another with the int(), float(), and complex() methods:
Example
Convert from one type to another:
x = 1 # int
y = 2.8 # float
z = 1j # complex
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
Note: You cannot convert complex numbers into another number type.
Random Number
Python does not have a random() function to make a random number, but Python has a built-in module
called random that can be used to make random numbers:
Example
Import the random module, and display a random number between 1 and 9:
import random
print(random.randrange(1, 10))
Python Lists
List
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set,
and Dictionary, all with different qualities and usage.
List Items
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has index [1] etc.
Ordered
When we say that lists are ordered, it means that the items have a defined order, and that order will not change.
If you add new items to a list, the new items will be placed at the end of the list.
Note: There are some list methods that will change the order, but in general: the order of the items will not change.
Changeable
The list is changeable, meaning that we can change, add, and remove items in a list after it has been created.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Example
Lists allow duplicate values:
List Length
To determine how many items a list has, use the len() function:
Example
Print the number of items in the list:
Example
String, int and boolean data types:
Example
A list with strings, integers and boolean values:
type()
From Python's perspective, lists are defined as objects with the data type 'list':
<class 'list'>
Example
What is the data type of a list?
Example
Using the list() constructor to make a List:
Negative Indexing
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
Example
Print the last item of the list:
Python list methods are built-in functions that allow us to perform various operations on lists, such
as adding, removing, or modifying elements. In this article, we’ll explore all Python list
methods with a simple example.
List Methods
Let’s look at different list methods in Python:
append(): Adds an element to the end of the list.
copy(): Returns a shallow copy of the list.
clear(): Removes all elements from the list.
count(): Returns the number of times a specified element appears in the list.
extend(): Adds elements from another list to the end of the current list.
index(): Returns the index of the first occurrence of a specified element.
insert(): Inserts an element at a specified position.
pop(): Removes and returns the element at the specified position (or the last element if no index
is specified).
remove(): Removes the first occurrence of a specified element.
reverse(): Reverses the order of the elements in the list.
sort(): Sorts the list in ascending order (by default).
Examples of List Methods
append():
Syntax: list_name.append(element)
In the code below, we will add an element to the list.
a = [1, 2, 3]
Output
[1, 2, 3, 4]
copy():
Syntax: list_name.copy()
In the code below, we will create a copy of a list.
a = [1, 2, 3]
Output
[1, 2, 3]
clear():
Syntax: list_name.clear()
In the code below, we will clear all elements from the list.
a = [1, 2, 3]
Output
[]
count():
Syntax: list_name.count(element)
In the code below, we will count the occurrences of a specific element in the list.
Python
a = [1, 2, 3, 2]
Output
2
extend():
Syntax: list_name.extend(iterable)
In the code below, we will extend the list by adding elements from another list.
a = [1, 2]
Output
[1, 2, 3, 4]
index():
Syntax: list_name.index(element)
In the code below, we will find the index of a specific element in the list.
a = [1, 2, 3]
Output
1
insert():
Syntax: list_name.insert(index, element)
In the code below, we will insert an element at a specific position in the list.
a = [1, 3]
# Insert 2 at index 1
a.insert(1, 2)
print(a)
Output
[1, 2, 3]
pop():
Syntax: list_name.pop(index)
In the code below, we will remove the last element from the list.
a = [1, 2, 3]
Output
[1, 2]
remove():
Syntax: list_name.remove(element)
In the code below, we will remove the first occurrence of a specified element from the list.
a = [1, 2, 3]
reverse():
Syntax: list_name.reverse()
In the code below, we will reverse the order of the elements in the list.
a = [1, 2, 3]
Output
[3, 2, 1]
sort():
Syntax: list_name.sort(key=None, reverse=False)
In the code below, we will sort the elements of the list in ascending order
a = [3, 1, 2]
Output
[1, 2, 3]
Python List Slicing
Python list slicing is fundamental concept that let us easily access specific elements in a list. In
this article, we’ll learn the syntax and how to use both positive and negative indexing for slicing
with examples.
Parameters:
start (optional): Index to begin the slice (inclusive). Defaults to 0 if omitted.
end (optional): Index to end the slice (exclusive). Defaults to the length of the list if omitted.
step (optional): Step size, specifying the interval between elements. Defaults to 1 if omitted
Table of Content
List Slicing Examples
o Get all the items from a list
o Get all items after a specific position
o Get all items before a specific position
o Get all items between two positions
o Get items at specified intervals
o Get the first n elements from a list
o Out-of-bound slicing
Negative Indexing
o Extract elements using negative indices
o Reverse a list using slicing
a = [1, 2, 3, 4, 5]
Output
[1, 2, 3, 4, 5]
Explanation: Using [:] without specifying start, end, or step returns all elements of the list.
Output
[30, 40, 50]
Explanation: The slice a[2:] starts from index 2 (third element) and continues to the end.
Output
[10, 20, 30]
Explanation: The slice a[:3] includes elements from the start up to index 3 (excluding 3).
Output
[20, 30, 40]
Explanation: The slice a[1:4] starts at index 1 and ends at index 4 (excluding 4).
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Output
[1, 3, 5, 7, 9]
Explanation: The slice a[::2] takes every second element from the list, starting from the
beginning.
Get the first n elements from a list
To get the first n elements of a list, specify the end index as n.
a = [10, 20, 30, 40, 50]
n = 3
Output
[10, 20, 30]
Out-of-bound slicing
In Python, list slicing allows out-of-bound indexing without raising errors. If we specify
indices beyond the list length, Python will simply return the available items.
Output
[10, 15]
Explanation: The slice a[1:10] starts at index 1 and attempts to reach index 10, but since the list
ends at index 2, it returns only the available elements.
Negative Indexing
Negative indexing is useful for accessing elements from the end of the list. The last
element has an index of -1, the second last element -2, and so on.
Extract elements using negative indices
This example shows how to use negative numbers to access elements from the list starting from
the end. Negative indexing makes it easy to get items without needing to know the exact length
of the list.
Python
a = [10, 20, 30, 40, 50]
Output
[20, 30, 40]
Explanation: Here, a[-4:-1] extracts elements starting from index -4 (which corresponds to 20)
and ends before -1 (which corresponds to 50).
Output
[500, 400, 300, 200, 100]
Python Tuples
Tuple
Tuples are used to store multiple items in a single variable.
Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set,
and Dictionary, all with different qualities and usage.
Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
Ordered
When we say that tuples are ordered, it means that the items have a defined order, and that order will not change.
Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created.
Allow Duplicates
Since tuples are indexed, they can have items with the same value:
Example
Tuples allow duplicate values:
Tuple Length
To determine how many items a tuple has, use the len() function:
Example
Print the number of items in the tuple:
Negative Indexing
Negative indexing means start from the end.
-1 refers to the last item, -2 refers to the second last item etc.
Example
Print the last item of the tuple:
Python Tuples is an immutable collection of that are more like lists. Python Provides a couple of
methods to work with tuples. In this article, we will discuss these two methods in detail with the
help of some examples.
Count() Method
The count() method of Tuple returns the number of times the given element appears in the tuple.
Syntax:
tuple.count(element)
Where the element is the element that is to be counted.
Example 1: Using the Tuple count() method
# Creating tuples
Tuple1 = (0, 1, 2, 3, 2, 3, 1, 3, 2)
res = Tuple1.count(3)
res = Tuple2.count('python')
Output:
Count of 3 in Tuple1 is: 3
Count of Python in Tuple2 is: 3
Example 2: Counting tuples and lists as elements in Tuples
# Creating tuples
Output:
Count of (2, 3) in Tuple is: 2
Count of [3, 2] in Tuple is: 1
Index() Method
The Index() method returns the first occurrence of the given element from the tuple.
Syntax:
tuple.index(element, start, end)
Parameters:
element: The element to be searched.
start (Optional): The starting index from where the searching is started
end (Optional): The ending index till where the searching is done
Note: This method raises a ValueError if the element is not found in the tuple.
Example 1: Using Tuple Index() Method
# Creating tuples
Tuple = (0, 1, 2, 3, 2, 3, 1, 3, 2)
res = Tuple.index(3)
res = Tuple.index(3, 4)
Output:
First occurrence of 3 is 3
First occurrence of 3 after 4th index is: 5
# Creating tuples
Tuple = (0, 1, 2, 3, 2, 3, 1, 3, 2)
res = Tuple.index(4)
Output:
ValueError: tuple.index(x): x not in tuple
Python Tuple – max() Method
While working with tuples many times we need to find the maximum element in the tuple, and for
this, we can also use max(). In this article, we will learn about the max() method used for tuples
in Python.
Example
Tuple =( 4, 2, 5, 6, 7, 5)
Input:
max(Tuple)
Output: 7
Explanation: The max() method returns the largest element of the given tuple.
Tuple = ( 1, 3, 4, 2, 5, 6 )
res = max(Tuple)
Output:
Maximum of Tuple is 6
# Creating tuples
res = max(Tuple)
print('Maximum of Tuple is', res)
Output:
Maximum of Tuple is GeeksForGeeks
# alphabets tuple
res = max(alphabets)
Output:
Maximum of Tuple is gfg
While working with tuples many times we need to find the minimum element in the tuple, and for
this, we can also use min(). In this article, we will learn about the min() method used for tuples
in Python.
Syntax of Tuple min() Method
Syntax: min(object)
Parameters:
object: Any iterable like Tuple, List, etc.
Return type: minimum element from the tuple.
Example
Tuple =( 4, 2, 5, 6, 7, 5)
Input: min(Tuple)
Output: 2
Explanation: The min() method returns the smallest element of the given tuple.
# Creating tuples
Output:
Minimum of Tuple is -2
# Creating tuples
res = min(Tuple)
# alphabets tuple
res = min(alphabets)
Output:
Minimum of Tuple is GFG
Tuple =( 1, 0, 4, 2, 5, 6, 7, 5)
print(len(Tuple))
Output :
8
Here we are declaring an empty tuple and printing its length in Python
empty_tuple = ()
length = len(empty_tuple)
print(length)
Output :
0
Tuple of Integers
# Creating tuples
Tuple = (1, 3, 4, 2, 5, 6)
res = len(Tuple)
print('Length of Tuple is', res)
Output :
Length of Tuple is 6
Tuple of Strings
Here we are finding the number of elements of the tuple that constitutes string elements
# Creating tuples
res = len(Tuple)
Output :
Length of Tuple is 4
Get the Length of the Nested Tuple
In this example, we have used created a tuple that consists of multiple tuples
# alphabets tuple
res = len(alphabets)
res_nested = len(alphabets[0])
Output :
Length of Tuple is 5
Length of nested tuple is 3
Tuple with Mixed DataTypes
length = len(mixed_tuple)
print(length)
Output :
4
Python has a set of built-in methods that you can use on strings.
Note: All string methods returns new values. They do not change the original string.
Method Description
endswith() Returns true if the string ends with the specified value
index() Searches the string for a specified value and returns the position of where it was fou
isalpha() Returns True if all characters in the string are in the alphabet
isascii() Returns True if all characters in the string are ascii characters
islower() Returns True if all characters in the string are lower case
isupper() Returns True if all characters in the string are upper case
join() Converts the elements of an iterable into a string
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where it wa
found
rindex() Searches the string for a specified value and returns the last position of where it wa
found
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
split() Splits the string at the specified separator, and returns a list
swapcase() Swaps cases, lower case becomes upper case and vice versa
zfill() Fills the string with a specified number of 0 values at the beginning
Note: All string methods returns new values. They do not change the original string.
Note: All string methods returns new values. They do not change the original string.
The below Python functions are used to change the case of the strings. Let’s look at some Python string
methods with examples:
Output
Converted String:
GEEKS FOR GEEKS
Converted String:
geeks for geeks
Converted String:
Geeks For Geeks
Converted String:
GEEkS fOR GEeKs
Original String
geeKs For geEkS
The format() method is a powerful tool that allows developers to create formatted strings by
embedding variables and values into placeholders within a template string. This method offers
a flexible and versatile way to construct textual output for a wide range of applications.
Python string format() function has been introduced for handling complex string formatting
more efficiently. Sometimes we want to make generalized print statements in that case instead
of writing print statements every time we use the concept of formatting.
Syntax: { }.format(value)
Parameters:
value : Can be an integer, floating point numeric constant, string, characters or even
variables.
Returntype: Returns a formatted string with the value passed as parameter in the placeholder
position.
name = "Ram"
age = 22
message = "My name is {0} and I am {1} years \
old. {1} is my favorite \
number.".format(name, age)
print(message)
Output
My name is Ram and I am 22 years old. 22 is my favorite number.
A Set in Python is a collection of unique elements which are unordered and mutable. Python
provides various functions to work with Set. In this article, we will see a list of all the functions
provided by Python to deal with Sets.
# set of letters
s = {'g', 'e', 'k', 's'}
# adding 's'
s.add('f')
s.discard('g')
s.remove('e')
s.clear()
Output
Set after updating: {'g', 'k', 's', 'e', 'f'}
Popped element k
Set after updating: {'s', 'f'}
Set after updating: set()
difference_update() Updates the existing caller set with the difference between two sets
Functions Name Description
intersection_update() Updates the existing caller set with the intersection of sets
issubset() Returns True if all elements of a set A are present in another set B
symmetric_difference() Returns a set which is the symmetric difference between the two sets
symmetric_difference_update() Updates the existing caller set with the symmetric difference of sets
Python has a set of built-in methods that you can use on sets.
These methods provide various functionalities for working with dictionaries in Python, making it
easier to manage and manipulate data stored in key-value pairs.
Note: For more information on Python Dictionary refer to Python Dictionary Tutorial.
Built-in Dictionary Methods in Python
In Python Dictionary we have various built-in functions that provide a wide range of operations for
working with dictionaries. These techniques enable efficient manipulation, access, and
transformation of dictionary data.
Lets Look at some Python dictionary methods with examples:
1. Dictionary clear() Method
The clear() method in Python is a built-in method that is used to remove all the elements (key-
value pairs) from a dictionary. It essentially empties the dictionary, leaving it with no key-value
pairs.
Output
{}
2. Dictionary get() Method
In Python, the get() method is a pre-built dictionary function that enables you to obtain the value
linked to a particular key in a dictionary. It is a secure method to access dictionary values without
causing a KeyError if the key isn’t present.
Output
Ram
None
3. Dictionary items() Method
In Python, the items() method is a built-in dictionary function that retrieves a view object containing
a list of tuples. Each tuple represents a key-value pair from the dictionary. This method is a
convenient way to access both the keys and values of a dictionary simultaneously, and it is highly
efficient.
Output
Age
19
4. Dictionary keys() Method
The keys() method in Python returns a view object with dictionary keys, allowing efficient access
and iteration.
Output
['Name', 'Age', 'Country']
Output
['Ram', '19', 'India']
5. Dictionary update() Method
Python’s update() method is a built-in dictionary function that updates the key-value pairs of a
dictionary using elements from another dictionary or an iterable of key-value pairs. With this
method, you can include new data or merge it with existing dictionary entries.
d1.update(d2)
print(d1)
Output
{'Name': 'Neha', 'Age': '22', 'Country': 'India'}
6. Dictionary values() Method
The values() method in Python returns a view object containing all dictionary values, which can be
accessed and iterated through efficiently.
Output
['Ram', '19', 'India']
Output
{'Name': 'Ram', 'Country': 'India'}
8. Dictionary popitem() Method
In Python, the popitem() method is a dictionary function that eliminates and returns a random (key,
value) pair from the dictionary.
As opposed to the pop() method which gets rid of a particular key-value pair based on a given key,
popitem() takes out and gives back a pair without requiring a key to be specified.
d.popitem()
print(d)
Output
{'Name': 'Ram', 'Age': '19'}
{'Name': 'Ram'}
Output:
You can also convert a bytes object to a list using
the list() constructor.
Output:
Bytearray
The bytearray data type is similar to bytes but is
mutable and allows for modification of its elements.
A bytearray object is created using the built-
in bytearray() function.
Output:
Bytearray is mutable
Output:
Memoryview
A memoryview object is created using the built-
in memoryview() function. It can take either
bytes or bytearray object as arguement
Output:
Type Conversion
Type Conversion
The act of changing an object’s (variable) data type
is known as type conversion.
Two types:
• Implicit Type Conversion.
• Explicit Type Conversion.
Implicit Type Conversion in Python
In Implicit type conversion of data types in Python,
the Python interpreter automatically converts one
data type to another without any user involvement.
This is to prevent loss of data
Example:
Explicit Type Conversion in Python
In Explicit Type Conversion in Python, the data type
is manually changed by the user as per their
requirement.
Here, there is a risk of data loss
Output:
Output:
Convert ASCII value to characters
Input-Output functions
Input-Output functions
With the print() function, you can display output in
various formats, while the input() function enables
interaction with users by gathering input during program
execution.
output
input
input : Reads a string from the user's keyboard.
• reads and returns an entire line of input
>>> print(name)
'Paris Hilton'
to read numbers, cast input result to an int or float
• If the user does not type a number, an error occurs.
• Example:
• Output:
% operator
The formatting using % is similar to that of ‘printf’ in
the C programming language.
%d –integer
%f – float
%s – string
%x –hexadecimal
%o – octal
Output: