KEMBAR78
PSPP Unit-2 Notes | PDF | Data Type | Integer (Computer Science)
0% found this document useful (0 votes)
6 views86 pages

PSPP Unit-2 Notes

The document provides an overview of Python's built-in data types, including text, numeric, sequence, mapping, set, boolean, binary, and none types. It explains numeric types (int, float, complex), lists, and their properties, methods, and slicing techniques. Additionally, it covers tuples and their characteristics as a collection type in Python.

Uploaded by

palamakularamesh
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)
6 views86 pages

PSPP Unit-2 Notes

The document provides an overview of Python's built-in data types, including text, numeric, sequence, mapping, set, boolean, binary, and none types. It explains numeric types (int, float, complex), lists, and their properties, methods, and slicing techniques. Additionally, it covers tuples and their characteristics as a collection type in Python.

Uploaded by

palamakularamesh
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
You are on page 1/ 86

Python Data Types

Built-in Data Types


In programming, data type is an important concept.

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:

Text Type: str

Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: dict

Set Types: set, frozenset

Boolean Type: bool

Binary Types: bytes, bytearray, memoryview

None Type: NoneType


Python Numbers

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:

ExampleGet your own Python Server


x = 1 # int
y = 2.8 # float
z = 1j # complex

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

#convert from int to float:


a = float(x)

#convert from float to int:


b = int(y)

#convert from int to complex:


c = complex(x)

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

mylist = ["apple", "banana", "cherry"]

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.

Lists are created using square brackets:

ExampleGet your own Python Server


Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)

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:

thislist = ["apple", "banana", "cherry", "apple", "cherry"]


print(thislist)

List Length
To determine how many items a list has, use the len() function:

Example
Print the number of items in the list:

thislist = ["apple", "banana", "cherry"]


print(len(thislist))
List Items - Data Types
List items can be of any data type:

Example
String, int and boolean data types:

list1 = ["apple", "banana", "cherry"]


list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]

A list can contain different data types:

Example
A list with strings, integers and boolean values:

list1 = ["abc", 34, True, 40, "male"]

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?

mylist = ["apple", "banana", "cherry"]


print(type(mylist))

The list() Constructor


It is also possible to use the list() constructor when creating a new list.

Example
Using the list() constructor to make a List:

thislist = list(("apple", "banana", "cherry")) # note the double round-brackets


print(thislist)

Python Collections (Arrays)


There are four collection data types in the Python programming language:

 List is a collection which is ordered and changeable. Allows duplicate members.


 Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
 Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate members.
 Dictionary is a collection which is ordered** and changeable. No duplicate members.
Access Items
List items are indexed and you can access them by referring to the index number:

ExampleGet your own Python Server


Print the second item of the list:

thislist = ["apple", "banana", "cherry"]


print(thislist[1])

Note: The first item has index 0.

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:

thislist = ["apple", "banana", "cherry"]


print(thislist[-1])
Python List methods


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]

# Add 4 to the end of the list


a.append(4)
print(a)

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]

# Create a copy of the list


b = a.copy()
print(b)

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]

# Remove all elements from the list


a.clear()
print(a)

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]

# Count occurrences of 2 in the list


print(a.count(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]

# Extend list a by adding elements from list [3, 4]


a.extend([3, 4])
print(a)

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]

# Find the index of 2 in the list


print(a.index(2))

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]

# Remove and return the last element in the list


a.pop()
print(a)

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]

# Remove the first occurrence of 2


a.remove(2)
print(a)
Output
[1, 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]

# Reverse the list order


a.reverse()
print(a)

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]

# Sort the list in ascending order


a.sort()
print(a)

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.

Python List Slicing Syntax


The syntax for slicing a list in Python is:
list_name[start : end : step]

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

List Slicing Examples


Let’s see how to use list slicing in Python with the examples below.
Get all the items from a list
To retrieve all items from a list, we can use slicing without specifying any parameters.

a = [1, 2, 3, 4, 5]

# Retrieve all elements in the list


print(a[:])

Output
[1, 2, 3, 4, 5]
Explanation: Using [:] without specifying start, end, or step returns all elements of the list.

Get all items after a specific position


To get all the items from a specific position to the end of the list, we can specify the start index and
leave the end blank.
a = [10, 20, 30, 40, 50]

# Retrieve elements starting


# from index 2 to the end of the list
subset = a[2:]
print(subset)

Output
[30, 40, 50]
Explanation: The slice a[2:] starts from index 2 (third element) and continues to the end.

Get all items before a specific position


To get all the items before a specific index, we can specify the end index while leaving start blank.

a = [10, 20, 30, 40, 50]

# Retrieve elements from the start up


# to index 3 (excluding 3th index)
subset = a[:3]
print(subset)

Output
[10, 20, 30]
Explanation: The slice a[:3] includes elements from the start up to index 3 (excluding 3).

Get all items between two positions


To extract elements between two specific positions, specify both the start and end indices
Python
a = [10, 20, 30, 40, 50]

# Retrieve elements from index 1


# to index 4 (excluding index 4)
subset = a[1:4]
print(subset)

Output
[20, 30, 40]
Explanation: The slice a[1:4] starts at index 1 and ends at index 4 (excluding 4).

Get items at specified intervals


To extract elements at specific intervals, use the step parameter.

a = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Retrieve every second element


# from the list starting from the beginning
subset = a[::2]
print(subset)

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

# Retrieve the first n elements of the list


subset = a[:n]
print(subset)

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.

a = [5, 10, 15]

# Attempt to slice beyond the list length


subset = a[1:10]
print(subset)

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]

# Retrieve elements from index -4


# to -1 (excluding index -1)
subset = a[-4:-1]
print(subset)

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).

Reverse a list using slicing


In this example, we’ll reverse the entire list using a slicing trick. By using a negative step value,
we can move through the list in reverse order.

a = [100, 200, 300, 400, 500]

# Reverse the entire list using negative step


b = a[::-1]
print(b)

Output
[500, 400, 300, 200, 100]

Python Tuples

mytuple = ("apple", "banana", "cherry")

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.

A tuple is a collection which is ordered and unchangeable.

Tuples are written with round brackets.

ExampleGet your own Python Server


Create a Tuple:

thistuple = ("apple", "banana", "cherry")


print(thistuple)
Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate values.

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:

thistuple = ("apple", "banana", "cherry", "apple", "cherry")


print(thistuple)

Tuple Length
To determine how many items a tuple has, use the len() function:

Example
Print the number of items in the tuple:

thistuple = ("apple", "banana", "cherry")


print(len(thistuple))

Python - Access Tuple Items


Access Tuple Items
You can access tuple items by referring to the index number, inside square brackets:

ExampleGet your own Python Server


Print the second item in the tuple:

thistuple = ("apple", "banana", "cherry")


print(thistuple[1])

Note: The first item has index 0.

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:

thistuple = ("apple", "banana", "cherry")


print(thistuple[-1])
Python Tuple Methods


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)

Tuple2 = ('python', 'geek', 'python',

'for', 'java', 'python')

# count the appearance of 3

res = Tuple1.count(3)

print('Count of 3 in Tuple1 is:', res)

# count the appearance of python

res = Tuple2.count('python')

print('Count of Python in Tuple2 is:', res)

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

Tuple = (0, 1, (2, 3), (2, 3), 1,

[3, 2], 'geeks', (0,))

# count the appearance of (2, 3)

res = Tuple.count((2, 3))

print('Count of (2, 3) in Tuple is:', res)

# count the appearance of [3, 2]

res = Tuple.count([3, 2])

print('Count of [3, 2] in Tuple is:', res)

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)

# getting the index of 3

res = Tuple.index(3)

print('First occurrence of 3 is', res)

# getting the index of 3 after 4th


# index

res = Tuple.index(3, 4)

print('First occurrence of 3 after 4th index is:', res)

Output:
First occurrence of 3 is 3
First occurrence of 3 after 4th index is: 5

Example 2: Using Tuple() method when the element is not found

# Creating tuples

Tuple = (0, 1, 2, 3, 2, 3, 1, 3, 2)

# getting the index of 3

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.

Python tuple max() Method


Syntax: max(object)
Parameters:
 object: Any iterable like Tuple, List, etc.
Return type: maximum element from the tuple.

Example 1: Using tuple max() Method


Here we are finding the max of a particular tuple.
# Creating tuples

Tuple = ( 1, 3, 4, 2, 5, 6 )

res = max(Tuple)

print('Maximum of Tuple is', res)

Output:
Maximum of Tuple is 6

Example 2: Using tuple max() Method for string elements


Here we are finding the maximum element out of the tuple that constitutes string elements based
on length.

# Creating tuples

Tuple = ( "Geeks", "For", "Geeks", "GeeksForGeeks")

res = max(Tuple)
print('Maximum of Tuple is', res)

Output:
Maximum of Tuple is GeeksForGeeks

Example 3: Using max for equal-length elements


Here we are finding the maximum element among the tuple of equal length elements. Where it
gives the lexicographically largest string.

# alphabets tuple

alphabets = ('GFG', 'gfg', 'gFg', 'GfG', 'Gfg')

res = max(alphabets)

print('Maximum of Tuple is', res)

Output:
Maximum of Tuple is gfg

Python Tuple – min() Method



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.

Using tuple min() Method


Here we are finding the minimum of a particular tuple.

# Creating tuples

Tuple = ( -1, 3, 4, -2, 5, 6 )


res = min(Tuple)

print('Minimum of Tuple is', res)

Output:
Minimum of Tuple is -2

Using tuple min() Method for string elements


Here we are finding the minimum element out of the tuple that constitutes of string elements
based on length

# Creating tuples

Tuple = ( "Geeks", "For", "Geeks", "GeeksForGeeks")

res = min(Tuple)

print('Minimum of Tuple is', res)


Output:
Minimum of Tuple is For

Using min for equal-length elements


Here we are finding the minimum element among the tuple of equal length elements. Where it
gives the lexicographically smallest string.

# alphabets tuple

alphabets = ('GFG', 'gfg', 'gFg', 'GfG', 'Gfg')

res = min(alphabets)

print('Minimum of Tuple is', res)

Output:
Minimum of Tuple is GFG

Python Tuple – len() Method





While working with tuples many times we need to find the length of the tuple, and, instead of
counting the number of elements with loops, we can also use Python len(). We will learn about
the len() method used for tuples in Python.
Example:

Tuple =( 1, 0, 4, 2, 5, 6, 7, 5)

print(len(Tuple))

Output :
8

Python tuple len() Method Syntax


Syntax: len(object)
Parameters:
 object: Any iterable like Tuple, List, etc.
Return type: the number of elements in the tuple.
Tuple len() in Python Examples
Empty Tuple

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

Here we are finding the length of a particular tuple.

# 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

Tuple = ("Geeks", "For", "Geeks", "GeeksForGeeks")

res = len(Tuple)

print('Length of Tuple is', res)

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

alphabets = (('G', 'F', 'G'), ('g', 'f', 'g'),

('g', 'F', 'g'), 'GfG', 'Gfg')

res = len(alphabets)

print('Length of Tuple is', res)

res_nested = len(alphabets[0])

print('Length of nested tuple is', res_nested)

Output :
Length of Tuple is 5
Length of nested tuple is 3
Tuple with Mixed DataTypes

In this example, we have used multiple types of data in the tuple.

mixed_tuple = ('apple', 3, True, 2.5)

length = len(mixed_tuple)

print(length)

Output :
4

Python String Methods

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

capitalize() Converts the first character to upper case

casefold() Converts string into lower case

center() Returns a centered string

count() Returns the number of times a specified value occurs in a string

encode() Returns an encoded version of the string

endswith() Returns true if the string ends with the specified value

expandtabs() Sets the tab size of the string


find() Searches the string for a specified value and returns the position of where it was fou

format() Formats specified values in a string

format_map() Formats specified values in a string

index() Searches the string for a specified value and returns the position of where it was fou

isalnum() Returns True if all characters in the string are alphanumeric

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

isdecimal() Returns True if all characters in the string are decimals


isdigit() Returns True if all characters in the string are digits

isidentifier() Returns True if the string is an identifier

islower() Returns True if all characters in the string are lower case

isnumeric() Returns True if all characters in the string are numeric

isprintable() Returns True if all characters in the string are printable

isspace() Returns True if all characters in the string are whitespaces

istitle() Returns True if the string follows the rules of a title

isupper() Returns True if all characters in the string are upper case
join() Converts the elements of an iterable into a string

ljust() Returns a left justified version of the string

lower() Converts a string into lower case

lstrip() Returns a left trim version of the string

maketrans() Returns a translation table to be used in translations

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

rjust() Returns a right justified version of the string

rpartition() Returns a tuple where the string is parted into three parts

rsplit() Splits the string at the specified separator, and returns a list

rstrip() Returns a right trim version of the string

split() Splits the string at the specified separator, and returns a list

splitlines() Splits the string at line breaks and returns a list


startswith() Returns true if the string starts with the specified value

strip() Returns a trimmed version of the string

swapcase() Swaps cases, lower case becomes upper case and vice versa

title() Converts the first character of each word to upper case

translate() Returns a translated string

upper() Converts a string into upper case

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.

Case Changing of Python String Methods

The below Python functions are used to change the case of the strings. Let’s look at some Python string
methods with examples:

 lower(): Converts all uppercase characters in a string into lowercase


 upper(): Converts all lowercase characters in a string into uppercase
 title(): Convert string to title case
 swapcase(): Swap the cases of all characters in a string
 capitalize(): Convert the first character of a string to uppercase

Example: Changing the case of Python String Methods


# Python3 program to show the
# working of upper() function
text = 'geeKs For geEkS'

# upper() function to convert


# string to upper case
print("\nConverted String:")
print(text.upper())

# lower() function to convert


# string to lower case
print("\nConverted String:")
print(text.lower())

# converts the first character to


# upper case and rest to lower case
print("\nConverted String:")
print(text.title())

# swaps the case of all characters in the string


# upper case character to lowercase and viceversa
print("\nConverted String:")
print(text.swapcase())

# convert the first character of a string to uppercase


print("\nConverted String:")
print(text.capitalize())

# original string never changes


print("\nOriginal String")
print(text)

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

Python String format() Method




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.

Python String Format() Syntax

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.

String Format() in Python Example

A simple demonstration of Python String format() Method in Python.

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.

Python Set Methods



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.

Adding and Removing elements


We can add and remove elements form the set with the help of the below functions –
 add(): Adds a given element to a set
 clear(): Removes all elements from the set
 discard(): Removes the element from the set
 pop(): Returns and removes a random element from the set
 remove(): Removes the element from the set
Example: Adding and removing elements from the Set.

# set of letters
s = {'g', 'e', 'k', 's'}

# adding 's'

s.add('f')

print('Set after updating:', s)

# Discarding element from the set

s.discard('g')

print('\nSet after updating:', s)

# Removing element from the set

s.remove('e')

print('\nSet after updating:', s)


# Popping elements from the set

print('\nPopped element', s.pop())

print('Set after updating:', s)

s.clear()

print('\nSet after updating:', s)

Output
Set after updating: {'g', 'k', 's', 'e', 'f'}

Set after updating: {'k', 's', 'e', 'f'}

Set after updating: {'k', 's', 'f'}

Popped element k
Set after updating: {'s', 'f'}
Set after updating: set()

Table of Python Set Methods

Functions Name Description

add() Adds a given element to a set

clear() Removes all elements from the set

copy() Returns a shallow copy of the set

difference() Returns a set that is the difference between two sets

difference_update() Updates the existing caller set with the difference between two sets
Functions Name Description

discard() Removes the element from the set

frozenset() Return an immutable frozenset object

intersection() Returns a set that has the intersection of all sets

intersection_update() Updates the existing caller set with the intersection of sets

isdisjoint() Checks whether the sets are disjoint or not

issubset() Returns True if all elements of a set A are present in another set B

issuperset() Returns True if all elements of a set A occupies set B

pop() Returns and removes a random element from the set

remove() Removes the element from the set


Functions Name Description

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

union() Returns a set that has the union of all sets

update() Adds elements to the set

Python has a set of built-in methods that you can use on sets.

Python Dictionary Methods



Python dictionary methods is collection of Python functions that operates on Dictionary.


Python Dictionary is like a map that is used to store data in the form of a key: value pair. Python
provides various built-in functions to deal with dictionaries. In this article, we will see a list of all the
functions provided by Python to work with dictionaries.
List of Python Dictionary Methods
Python provides several built-in methods for dictionaries that allow for efficient manipulation,
access, and transformation of dictionary data. Here’s a list of some important Python dictionary
methods:
Functions Name Descriptions

clear() Removes all items from the dictionary

copy() Returns a shallow copy of the dictionary

fromkeys() Creates a dictionary from the given sequence

get() Returns the value for the given key

Return the list with all dictionary keys with


items() values

Returns a view object that displays a list of all


keys() the keys in the dictionary in order of insertion

Returns and removes the element with the given


pop() key
Functions Name Descriptions

Returns and removes the key-value pair from the


popitem() dictionary

Returns the value of a key if the key is in the


dictionary else inserts the key with a value to the
setdefault() dictionary

Returns a view object containing all dictionary


values, which can be accessed and iterated
values() through efficiently

Updates the dictionary with the elements from


another dictionary or an iterable of key-value
pairs. With this method, you can include new
update() data or merge it with existing dictionary entries

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.

my_dict = {'1': 'Geeks', '2': 'For', '3': 'Geeks'}


my_dict.clear()
print(my_dict)

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.

d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}


print(d.get('Name'))
print(d.get('Gender'))

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.

d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}


print(list(d.items())[1][0])
print(list(d.items())[1][1])

Output
Age
19
4. Dictionary keys() Method
The keys() method in Python returns a view object with dictionary keys, allowing efficient access
and iteration.

d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}


print(list(d.keys()))

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 = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}


d2 = {'Name': 'Neha', 'Age': '22'}

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.

d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}


print(list(d.values()))

Output
['Ram', '19', 'India']

7. Dictionary pop() Method


In Python, the pop() method is a pre-existing dictionary method that removes and retrieves the
value linked with a given key from a dictionary. If the key is not present in the dictionary, you can
set an optional default value to be returned.

d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}


d.pop('Age')
print(d)

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 = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}


d.popitem()
print(d)

d.popitem()
print(d)

Output
{'Name': 'Ram', 'Age': '19'}
{'Name': 'Ram'}

Binary types (bytearray, bytes, memory view)


Binary types (byte array, bytes, memory view)
 The binary data types in Python are used to
represent binary data comprising sequences of 0s
and 1s.
 There are three main binary data types in Python:
bytes, bytearray, and memoryview.
Bytes
 The bytes data type is an immutable sequence of
bytes representing a sequence of binary data.
 You can create a bytes object in Python by prefixing a string
with a "b" or calling the bytes()

 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

Example: with byte Output:


 Example : with bytearray

 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

>>> name = input("What's your


name?")
What's your name? Paris Hilton

>>> 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:

You might also like