0% found this document useful (0 votes)
33 views

Unit Iv

Strings are a popular data type in Python that can be created using single quotes, double quotes, or triple quotes for multiline strings. Strings support various operations like accessing characters using indexes, slicing substrings, updating strings, and string formatting. Escape characters can be used to represent non-printable characters. Operators like + for concatenation and % for string formatting are also supported.

Uploaded by

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

Unit Iv

Strings are a popular data type in Python that can be created using single quotes, double quotes, or triple quotes for multiline strings. Strings support various operations like accessing characters using indexes, slicing substrings, updating strings, and string formatting. Escape characters can be used to represent non-printable characters. Operators like + for concatenation and % for string formatting are also supported.

Uploaded by

Michael godson
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

PYTHON

PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

PYTHON - STRINGS
Strings are amongst the most popular types in Python. We can create them simply by enclosing
characters in quotes. Python treats single quotes the same as double quotes. Creating strings is as
simple as assigning a value to a variable. For example −

var1 = 'Hello World!'


var2 = "Python Programming"

Accessing Values in Strings

Python does not support a character type; these are treated as strings of length one, thus also considered
a substring.

To access substrings, use the square brackets for slicing along with the index or indices to obtain your
substring. For example −

var1 = 'Hello World!'


var2 = "Python Programming"

print "var1[0]: ", var1[0]


print "var2[1:5]: ", var2[1:5]

When the above code is executed, it produces the following result −

var1[0]: H
var2[1:5]: ytho

Updating Strings

You can "update" an existing string by (re)assigning a variable to another string. The new value can
be related to its previous value or to a completely different string altogether. For example −

var1 = 'Hello World!'


print "Updated String :- ", var1[:6] + 'Python'

When the above code is executed, it produces the following result −

Updated String :- Hello Python


1
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

Escape Characters

Following table is a list of escape or non-printable characters that can be represented with backslash
notation.

An escape character gets interpreted; in a single quoted as well as double quoted strings.

Backslash Hexadecimal Description


notation character

\a 0x07 Bell or alert

\b 0x08 Backspace

\cx Control-x

\C-x Control-x

\e 0x1b Escape

\f 0x0c Formfeed

\M-\C-x Meta-Control-x

\n 0x0a Newline

\nnn Octal notation, where n is in the range 0.7

\r 0x0d Carriage return

\s 0x20 Space

\t 0x09 Tab

\v 0x0b Vertical tab

\x Character x

\xnn Hexadecimal notation, where n is in the range 0.9, a.f,


or A.F
2
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

String Special Operators

Assume string variable a holds 'Hello' and variable b holds 'Python', then −

Operator Description Example

+ Concatenation - Adds values on either side of the a + b will give HelloPython


operator

* Repetition - Creates new strings, concatenating a*2 will give -HelloHello


multiple copies of the same string

[] Slice - Gives the character from the given index a[1] will give e

[:] Range Slice - Gives the characters from the given a[1:4] will give ell
range

in Membership - Returns true if a character exists in H in a will give 1


the given string

not in Membership - Returns true if a character does not M not in a will give 1
exist in the given string

r/R Raw String - Suppresses actual meaning of Escape print r'\n' prints \n and print
characters. The syntax for raw strings is exactly the R'\n'prints \n
same as for normal strings with the exception of the
raw string operator, the letter "r," which precedes
the quotation marks. The "r" can be lowercase (r) or
uppercase (R) and must be placed immediately
preceding the first quote mark.

% Format - Performs String formatting See at next section


3
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

String Formatting Operator

One of Python's coolest features is the string format operator %. This operator is unique to strings and
makes up for the pack of having functions from C's printf() family. Following is a simple example −

print "My name is %s and weight is %d kg!" % ('Zara', 21)

When the above code is executed, it produces the following result −

My name is Zara and weight is 21 kg!

Here is the list of complete set of symbols which can be used along with % −

Format Symbol Conversion

%c character

%s string conversion via str() prior to formatting

%i signed decimal integer

%d signed decimal integer

%u unsigned decimal integer

%o octal integer

%x hexadecimal integer (lowercase letters)

%X hexadecimal integer (UPPERcase letters)

%e exponential notation (with lowercase 'e')

%E exponential notation (with UPPERcase 'E')

%f floating point real number

%g the shorter of %f and %e

%G the shorter of %f and %E


4
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

Other supported symbols and functionality are listed in the following table −

Symbol Functionality

* argument specifies width or precision

- left justification

+ display the sign

<sp> leave a blank space before a positive number

# add the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X',
depending on whether 'x' or 'X' were used.

0 pad from left with zeros (instead of spaces)

% '%%' leaves you with a single literal '%'

(var) mapping variable (dictionary arguments)

m.n. m is the minimum total width and n is the number of digits to display
after the decimal point (if appl.)

Triple Quotes

Python's triple quotes comes to the rescue by allowing strings to span multiple lines, including
verbatim NEWLINEs, TABs, and any other special characters.

The syntax for triple quotes consists of three consecutive single or double quotes.

para_str = """this is a long string that is made up of


several lines and non-printable characters such as
TAB ( \t ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [ \n ], or just a NEWLINE within
the variable assignment will also show up.
"""
print para_str
5
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

When the above code is executed, it produces the following result. Note how every single special
character has been converted to its printed form, right down to the last NEWLINE at the end of the
string between the "up." and closing triple quotes. Also note that NEWLINEs occur either with an
explicit carriage return at the end of a line or its escape code (\n) −

this is a long string that is made up of


several lines and non-printable characters such as
TAB ( ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [
], or just a NEWLINE within
the variable assignment will also show up.

Raw strings do not treat the backslash as a special character at all. Every character you put into a raw
string stays the way you wrote it −

print 'C:\\nowhere'

When the above code is executed, it produces the following result −

C:\nowhere

Now let's make use of raw string. We would put expression in r'expression' as follows −

print r'C:\\nowhere'

When the above code is executed, it produces the following result −

C:\\nowhere
STRING OPERATIONS IN PYTHON
Strings are sequences of characters. There are numerous algorithms for processing strings, including
for searching, sorting, comparing and transforming. Python strings are "immutable" which means they
cannot be changed after they are created. To create a string, put the sequence of characters inside either
single quotes, double quotes, or triple quotes and then assign it to a variable.
str = 'Hellow World!'
str = "Hellow World!"
str = """Sunday
Monday
Tuesday"""
6
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

Access characters in a string


In order ot access characters from String, use the square brackets [] for slicing along with the index or
indices to obtain your characters. Python String index starts from 0.
str = 'Hellow World!'
print(str [0]) # output is "H"
print(str [7]) # output is "W"
print(str [0:6]) #output is Hellow
print(str [7:12]) #output is World

Python allows negative indexing for its sequences.


The index of -1 refers to the last item, -2 to the second last item and so on.

print(str [0:-6]) # output is Hellow


print(str [7:-1]) # output is World

String Concatenation
Joining of two or more strings into a single one is called concatenation. Python uses "+" operator for
joining one or more strings
str1 = 'Hellow '
str2 = ' World!'
print(str1 + str2)

output
Hellow World!

Reverse a String
In Python Strings are sliceable. Slicing a string gives you a new string from one point in the string,
backwards or forwards, to another point, by given increments. They take slice notation or a slice object
in a subscript:
string[subscript]
The subscript creates a slice by including a colon within the braces:
string[begin:end:step]
It works by doing [begin:end:step] - by leaving begin and end off and specifying a step of -1, it reverses
a string.
7
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

str = 'Python String'


print(str[::-1])
output
gnirtS nohtyP

STRING METHODS
Python has several built-in methods associated with the string data type. These methods let us easily
modify and manipulate strings. Built-in methods are those that are defined in the Python programming
language and are readily available for us to use. Here are some of the most common string methods.

Python String len() method


String len() method return the length of the string.
str = "Hellow World!"
print(len(str))
output
13

Python String count() method


String count() method returns the number of occurrences of a substring in the given string.

str = "Python is Object Oriented"


substr = "Object"
print(str.count(substr)) # return 1, becasue the word Object exist 1 time in str
output
1

Python String index() method


String index() method returns the index of a substring inside the given string.
index(substr,start,end)

end(optional) by default its equal to the length of the string.


str = "Python is Object Oriented"
substr = "is"
print(str.index(substr))
8
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

output
7

Python String upper() method


String upper() convert the given string into Uppercase letters and return new string.

str = "Python is Object Oriented"


print(str.upper())

output
PYTHON IS OBJECT ORIENTED

Python String lower() method


String lower() convert the given string into Lowercase letters and return new string.

str = "Python is Object Oriented"


print(str.lower())
output
python is object oriented

Python String startswith() method


String startswith() method returns Boolean TRUE, if the string Starts with the specified substring
otherwise, it will return False.
str = "Python is Object Oriented"
print(str.startswith("Python"))
print(str.startswith("Object"))

output
True
False
Python String endswith() method
String endswith() method returns Boolean TRUE, if the string Ends with the specified substring
otherwise, it will return False.
9
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

str = "Python is Object Oriented"


print(str.endswith("Oriented"))
print(str.endswith("Object"))
output
True
False

Python String split() method


String split() method break up a string into smaller strings based on a delimiter or character.
str = 'Python is Object Oriented'
print(str.split())
output
['Python', 'is', 'Object', 'Oriented']
example
str = 'Python,is,Object,Oriented'
print(str.split(','))
output
['Python', 'is', 'Object', 'Oriented']
example
str = 'Python,is,Object,Oriented'
print(str.split(',',2))
output
['Python', 'is', 'Object,Oriented']

Python returned split string as a List


str = 'Python,is,Object,Oriented'
sList = str.split(',')
for temp in sList:
print (temp)
output
Python
is
Object
10

Oriented
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

Python String join() method


String join() is a string method which returns a string concatenated with the elements of an iterable.
str = "Python is Object Oriented"
tmp = "-"
print (tmp.join(str))
output
P-y-t-h-o-n- -i-s- -O-b-j-e-c-t- -O-r-i-e-n-t-e-d

Python String find() method


String find() return the index position of the first occurrence of a specified string. It will return -1, if
the specified string is not found.
str = "Python is Object Oriented"
st = "Object"
print (str.find(st))
print (str.find(st,20)) #finding from 20th position
output
10
-1

Python String strip() method


String strip() remove the specified characters from both Right hand side and Left hand side of a string
(By default, White spaces) and returns the new string.

str = " Python is Object Oriented "


print (str.strip())
output
Python is Object Oriented

Python String rstrip() method


String rstrip() returns a copy of the string with trailing characters removed.

str = " Python is Object Oriented "


print (str.rstrip())
11
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

output
Python is Object Oriented

Python String lstrip() method


String lstrip() returns a copy of the string with leading characters removed.
str = " Python is Object Oriented "
print (str.lstrip())
output
Python is Object Oriented

PYTHON LIST
Lists are just like dynamically sized arrays, declared in other languages (vector in C++ and ArrayList
in Java). Lists need not be homogeneous always which makes it the most powerful tool in Python. A
single list may contain DataTypes like Integers, Strings, as well as Objects. Lists are mutable, and
hence, they can be altered even after their creation.
List in Python are ordered and have a definite count. The elements in a list are indexed according to
a definite sequence and the indexing of a list is done with 0 being the first index. Each element in the
list has its definite place in the list, which allows duplicating of elements in the list, with each element
having its own distinct place and credibility.

Create Python Lists

In Python, a list is created by placing elements inside square brackets [], separated by commas.

# list of integers
my_list = [1, 2, 3]

A list can have any number of items and they may be of different types (integer, float, string, etc.).

# empty list
my_list = []
# list with mixed data types
my_list = [1, "Hello", 3.4]
12
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

A list can also have another list as an item. This is called a nested list.

# nested list
my_list = ["mouse", [8, 4, 6], ['a']]

Access List Elements

There are various ways in which we can access the elements of a list.

List Index

We can use the index operator [] to access an item in a list. In Python, indices start at 0. So, a list having
5 elements will have an index from 0 to 4.
Trying to access indexes other than these will raise an IndexError. The index must be an integer. We
can't use float or other types, this will result in TypeError.
Nested lists are accessed using nested indexing.

my_list = ['p', 'r', 'o', 'b', 'e']


# first item
print(my_list[0]) # p
# third item
print(my_list[2]) # o
# fifth item
print(my_list[4]) # e
# Nested List
n_list = ["Happy", [2, 0, 1, 5]]
# Nested indexing
print(n_list[0][1])
print(n_list[1][3])
# Error! Only integer can be used for indexing
print(my_list[4.0])
13
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

Output

p
o
e
a
5
Traceback (most recent call last):
File "<string>", line 21, in <module>
TypeError: list indices must be integers or slices, not float

Updating List values

Lists are the most versatile data structures in Python since they are mutable, and their values can be
updated by using the slice and assignment operator.Python also provides append() and insert() methods,
which can be used to add values to the list.

Consider the following example to update the values inside the list.

list = [1, 2, 3, 4, 5, 6]
print(list)
# It will assign value to the value to the second index
list[2] = 10
print(list)
# Adding multiple-element
list[1:3] = [89, 78]
print(list)
# It will add value at the end of the list
list[-1] = 25
print(list)

Output:

[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]
14
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

The list elements can also be deleted by using the del keyword. Python also provides us
the remove() method if we do not know which element is to be deleted from the list.

Consider the following example to delete the list elements.

list = [1, 2, 3, 4, 5, 6]
print(list)
# It will assign value to the value to second index
list[2] = 10
print(list)
# Adding multiple element
list[1:3] = [89, 78]
print(list)
# It will add value at the end of the list
list[-1] = 25
print(list)

Output:

[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]

Python List Operations

The concatenation (+) and repetition (*) operators work in the same way as they were working with the
strings.Let's see how the list responds to various operators.

Consider a Lists l1 = [1, 2, 3, 4], and l2 = [5, 6, 7, 8] to perform operation.

Operator Description Example

Repetition The repetition operator enables the list L1*2 = [1, 2, 3, 4, 1, 2, 3, 4]


elements to be repeated multiple times.

Concatenation It concatenates the list mentioned on either l1+l2 = [1, 2, 3, 4, 5, 6, 7, 8]


15
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

side of the operator.

Membership It returns true if a particular item exists in a print(2 in l1) prints True.
particular list otherwise false.

Iteration The for loop is used to iterate over the list for i in l1:
elements. print(i)
Output
1
2
3
4

Length It is used to get the length of the list len(l1) = 4

Python Tuple

Python Tuple is used to store the sequence of immutable Python objects. The tuple is similar to lists
since the value of the items stored in the list can be changed, whereas the tuple is immutable, and the
value of the items stored in the tuple cannot be changed.

Creating a Tuple

A tuple is created by placing all the items (elements) inside parentheses (), separated by commas. The
parentheses are optional, however, it is a good practice to use them.A tuple can have any number of
items and they may be of different types (integer, float, list, string, etc.).

# Different types of tuples

# Empty tuple
my_tuple = ()
print(my_tuple)

# Tuple having integers


my_tuple = (1, 2, 3)
print(my_tuple)
16

# tuple with mixed datatypes


Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

my_tuple = (1, "Hello", 3.4)


print(my_tuple)

# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)

Output

()
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))

Python Tuple inbuilt functions

SN Function Description

1 cmp(tuple1, It compares two tuples and returns true if tuple1 is greater than
tuple2) tuple2 otherwise false.

2 len(tuple) It calculates the length of the tuple.

3 max(tuple) It returns the maximum element of the tuple

4 min(tuple) It returns the minimum element of the tuple.

5 tuple(seq) It converts the specified sequence to the tuple.


17
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

PYTHON DICTIONARY

Python Dictionary is used to store the data in a key-value pair format. The dictionary is the data type
in Python, which can simulate the real-life data arrangement where some specific value exists for some
particular key. It is the mutable data-structure. The dictionary is defined into element Keys and values.

o Keys must be a single element


o Value can be any type such as list, tuple, integer, etc.

In other words, we can say that a dictionary is the collection of key-value pairs where the value can be
any Python object. In contrast, the keys are the immutable Python object, i.e., Numbers, string, or tuple.

Creating the dictionary

The dictionary can be created by using multiple key-value pairs enclosed with the curly brackets {},
and each key is separated from its value by the colon (:).The syntax to define the dictionary is given
below.

Syntax:

Dict = {"Name": "Tom", "Age": 22}

In the above dictionary Dict, The keys Name and Age are the string that is an immutable object.

Let's see an example to create a dictionary and print its content.

Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


print(type(Employee))
print("printing Employee data .... ")
print(Employee)

Output

<class 'dict'>
Printing Employee data ....
{'Name': 'John', 'Age': 29, 'salary': 25000, 'Company': 'GOOGLE'}
18
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

Python provides the built-in function dict() method which is also used to create dictionary. The empty
curly braces {} is used to create empty dictionary.

# Creating an empty Dictionary


Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Java', 2: 'T', 3:'Point'})
print("\nCreate Dictionary by using dict(): ")
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Devansh'), (2, 'Sharma')])
print("\nDictionary with each item as a pair: ")
print(Dict)

Output:

Empty Dictionary:
{}

Create Dictionary by using dict():


{1: 'Java', 2: 'T', 3: 'Point'}

Dictionary with each item as a pair:


{1: 'Devansh', 2: 'Sharma'}

Accessing the dictionary values

We have discussed how the data can be accessed in the list and tuple by using the indexing. However,
the values can be accessed in the dictionary by using the keys as keys are unique in the dictionary. The
dictionary values can be accessed in the following way.
19

Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

print(type(Employee))
print("printing Employee data .... ")
print("Name : %s" %Employee["Name"])
print("Age : %d" %Employee["Age"])
print("Salary : %d" %Employee["salary"])
print("Company : %s" %Employee["Company"])

Output:

<class 'dict'>
printing Employee data ....
Name : John
Age : 29
Salary : 25000
Company : GOOGLE

Python provides us with an alternative to use the get() method to access the dictionary values. It would
give the same result as given by the indexing.

Adding dictionary values

The dictionary is a mutable data type, and its values can be updated by using the specific keys. The
value can be updated along with key Dict[key] = value. The update() method is also used to update an
existing value. Note: If the key-value already present in the dictionary, the value gets updated.
Otherwise, the new keys added in the dictionary.

Let's see an example to update the dictionary values.

Example - 1:

# Creating an empty Dictionary


Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Adding elements to dictionary one at a time
Dict[0] = 'Peter'
20

Dict[2] = 'Joseph'
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

Dict[3] = 'Ricky'
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Adding set of values
# with a single Key
# The Emp_ages doesn't exist to dictionary
Dict['Emp_ages'] = 20, 33, 24
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Updating existing Key's Value
Dict[3] = 'JavaTpoint'
print("\nUpdated key value: ")
print(Dict)

Output:

Empty Dictionary:
{}

Dictionary after adding 3 elements:


{0: 'Peter', 2: 'Joseph', 3: 'Ricky'}

Dictionary after adding 3 elements:


{0: 'Peter', 2: 'Joseph', 3: 'Ricky', 'Emp_ages': (20, 33, 24)}

Updated key value:


{0: 'Peter', 2: 'Joseph', 3: 'JavaTpoint', 'Emp_ages': (20, 33, 24)}

Example - 2:

Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


print(type(Employee))
print("printing Employee data .... ")
print(Employee)
21

print("Enter the details of the new employee....");


Employee["Name"] = input("Name: ");
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

Employee["Age"] = int(input("Age: "));


Employee["salary"] = int(input("Salary: "));
Employee["Company"] = input("Company:");
print("printing the new data");
print(Employee)

Output:

Empty Dictionary:
{}

Dictionary after adding 3 elements:


{0: 'Peter', 2: 'Joseph', 3: 'Ricky'}

Dictionary after adding 3 elements:


{0: 'Peter', 2: 'Joseph', 3: 'Ricky', 'Emp_ages': (20, 33, 24)}

Updated key value:


{0: 'Peter', 2: 'Joseph', 3: 'JavaTpoint', 'Emp_ages': (20, 33, 24)}

Deleting elements using del keyword

The items of the dictionary can be deleted by using the del keyword as given below.

Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


print(type(Employee))
print("printing Employee data .... ")
print(Employee)
print("Deleting some of the employee data")
del Employee["Name"]
del Employee["Company"]
print("printing the modified information ")
print(Employee)
print("Deleting the dictionary: Employee");
del Employee
22

print("Lets try to print it again ");


Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

print(Employee)

Output:

<class 'dict'>
printing Employee data ....
{'Name': 'John', 'Age': 29, 'salary': 25000, 'Company': 'GOOGLE'}
Deleting some of the employee data
printing the modified information
{'Age': 29, 'salary': 25000}
Deleting the dictionary: Employee
Lets try to print it again
NameError: name 'Employee' is not defined

The last print statement in the above code, it raised an error because we tried to print the Employee
dictionary that already deleted.

o Using pop() method

The pop() method accepts the key as an argument and remove the associated value. Consider the
following example.

# Creating a Dictionary
Dict = {1: 'JavaTpoint', 2: 'Peter', 3: 'Thomas'}
# Deleting a key
# using pop() method
pop_ele = Dict.pop(3)
print(Dict)

Output:

{1: 'JavaTpoint', 2: 'Peter'}

Python also provides a built-in methods popitem() and clear() method for remove elements from the
dictionary. The popitem() removes the arbitrary element from a dictionary, whereas the clear() method
removes all elements to the whole dictionary.
23
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

Built-in Dictionary functions

The built-in python dictionary methods along with the description are given below.

SN Function Description

1 cmp(dict1, It compares the items of both the dictionary and returns true if the first
dict2) dictionary values are greater than the second dictionary, otherwise it returns
false.

2 len(dict) It is used to calculate the length of the dictionary.

3 str(dict) It converts the dictionary into the printable string representation.

4 type(variable) It is used to print the type of the passed variable.

Built-in Dictionary methods

The built-in python dictionary methods along with the description are given below.

SN Method Description

1 dic.clear() It is used to delete all the items of the dictionary.

2 dict.copy() It returns a shallow copy of the dictionary.

3 dict.fromkeys(iterable, value = Create a new dictionary from the iterable with the values
None, /) equal to value.

4 dict.get(key, default = "None") It is used to get the value specified for the passed key.

5 dict.has_key(key) It returns true if the dictionary contains the specified key.

6 dict.items() It returns all the key-value pairs as a tuple.

7 dict.keys() It returns all the keys of the dictionary.

8 dict.setdefault(key,default= It is used to set the key to the default value if the key is not
"None") specified in the dictionary

9 dict.update(dict2) It updates the dictionary by adding the key-value pair of


24

dict2 to this dictionary.


Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

10 dict.values() It returns all the values of the dictionary.

11 len() It returns length of the dictionary.

13 pop() It removes element from the dictionary.

14 count() It returns count elements of the dictionary.

15 index() It returns index value

PYTHON SET

A Python set is the collection of the unordered items. Each element in the set must be unique,
immutable, and the sets remove the duplicate elements. Sets are mutable which means we can modify
it after its creation. Unlike other collections in Python, there is no index attached to the elements of the
set, i.e., we cannot directly access any element of the set by the index. However, we can print them all
together, or we can get the list of elements by looping through the set.

Creating a set

The set can be created by enclosing the comma-separated immutable items with the curly braces {}.
Python also provides the set() method, which can be used to create the set by the passed sequence.

Example 1: Using curly braces


Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sun
day"}
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)

Output:

{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday', 'Wednesday'}


<class 'set'>
25

looping through the set elements ...


Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday

Example 2: Using set() method


Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday
"])
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)

Output:

{'Friday', 'Wednesday', 'Thursday', 'Saturday', 'Monday', 'Tuesday', 'Sunday'}


<class 'set'>
looping through the set elements ...
Friday
Wednesday
Thursday
Saturday
Monday
Tuesday
Sunday

It can contain any type of element such as integer, float, tuple etc. But mutable elements (list, dictionary,
set) can't be a member of set. Consider the following example.

# Creating a set which have immutable elements


26

set1 = {1,2,3, "JavaTpoint", 20.5, 14}


Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

print(type(set1))
#Creating a set which have mutable element
set2 = {1,2,3,["Javatpoint",4]}
print(type(set2))

Output:

<class 'set'>

Traceback (most recent call last)


<ipython-input-5-9605bb6fbc68> in <module>
4
5 #Creating a set which holds mutable elements
----> 6 set2 = {1,2,3,["Javatpoint",4]}
7 print(type(set2))

TypeError: unhashable type: 'list'

In the above code, we have created two sets, the set set1 have immutable elements and set2 have one
mutable element as a list. While checking the type of set2, it raised an error, which means set can
contain only immutable elements.

Creating an empty set is a bit different because empty curly {} braces are also used to create a dictionary
as well. So Python provides the set() method used without an argument to create an empty set.

# Empty curly braces will create dictionary


set3 = {}
print(type(set3))

# Empty set using set() function


set4 = set()
print(type(set4))

Output:
27

<class 'dict'>
<class 'set'>
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

Let's see what happened if we provide the duplicate element to the set.

set5 = {1,2,4,4,5,8,9,9,10}
print("Return set with unique elements:",set5)

Output:

Return set with unique elements: {1, 2, 4, 5, 8, 9, 10}

In the above code, we can see that set5 consisted of multiple duplicate elements when we printed it
remove the duplicity from the set.

Adding items to the set

Python provides the add() method and update() method which can be used to add some particular item
to the set. The add() method is used to add a single element whereas the update() method is used to add
multiple elements to the set. Consider the following example.

Example: 1 - Using add() method


Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nAdding other months to the set...");
Months.add("July");
Months.add ("August");
print("\nPrinting the modified set...");
print(Months)
print("\nlooping through the set elements ... ")
for i in Months:
print(i)

Output:

printing the original set ...


{'February', 'May', 'April', 'March', 'June', 'January'}
28

Adding other months to the set...


Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

Printing the modified set...


{'February', 'July', 'May', 'April', 'March', 'August', 'June', 'January'}

looping through the set elements ...


February
July
May
April
March
August
June
January

To add more than one item in the set, Python provides the update() method. It accepts iterable as an
argument.

Consider the following example.

Example - 2 Using update() function


Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nupdating the original set ... ")
Months.update(["July","August","September","October"]);
print("\nprinting the modified set ... ")
print(Months);

Output:

printing the original set ...


{'January', 'February', 'April', 'May', 'June', 'March'}

updating the original set ...


printing the modified set ...
29

{'January', 'February', 'April', 'August', 'October', 'May', 'June', 'July', 'September', 'March'}
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

Removing items from the set

Python provides the discard() method and remove() method which can be used to remove the items
from the set. The difference between these function, using discard() function if the item does not exist
in the set then the set remain unchanged whereas remove() method will through an error.

Consider the following example.

Example-1 Using discard() method


months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nRemoving some months from the set...");
months.discard("January");
months.discard("May");
print("\nPrinting the modified set...");
print(months)
print("\nlooping through the set elements ... ")
for i in months:
print(i)

Output:

printing the original set ...


{'February', 'January', 'March', 'April', 'June', 'May'}

Removing some months from the set...

Printing the modified set...


{'February', 'March', 'April', 'June'}

looping through the set elements ...


February
March
April
30

June
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

Python provides also the remove() method to remove the item from the set. Consider the following
example to remove the items using remove() method.

Example-2 Using remove() function


months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nRemoving some months from the set...");
months.remove("January");
months.remove("May");
print("\nPrinting the modified set...");
print(months)

Output:

printing the original set ...


{'February', 'June', 'April', 'May', 'January', 'March'}

Removing some months from the set...

Printing the modified set...


{'February', 'June', 'April', 'March'}

We can also use the pop() method to remove the item. Generally, the pop() method will always remove
the last item but the set is unordered, we can't determine which element will be popped from set.

Consider the following example to remove the item from the set using pop() method.

Months = set(["January","February", "March", "April", "May", "June"])


print("\nprinting the original set ... ")
print(Months)
print("\nRemoving some months from the set...");
Months.pop();
Months.pop();
print("\nPrinting the modified set...");
31

print(Months)
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

Output:

printing the original set ...


{'June', 'January', 'May', 'April', 'February', 'March'}

Removing some months from the set...

Printing the modified set...


{'May', 'April', 'February', 'March'}

In the above code, the last element of the Month set is March but the pop() method removed the June
and January because the set is unordered and the pop() method could not determine the last element
of the set.

Python provides the clear() method to remove all the items from the set.

Consider the following example.

Months = set(["January","February", "March", "April", "May", "June"])


print("\nprinting the original set ... ")
print(Months)
print("\nRemoving all the items from the set...");
Months.clear()
print("\nPrinting the modified set...")
print(Months)

Output:

printing the original set ...


{'January', 'May', 'June', 'April', 'March', 'February'}

Removing all the items from the set...

Printing the modified set...


set()
32
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

Python Set Operations

Set can be performed mathematical operation such as union, intersection, difference, and symmetric
difference. Python provides the facility to carry out these operations with operators or methods. We
describe these operations as follows.

Union of two Sets

The union of two sets is calculated by using the pipe (|) operator. The union of the two sets contains all
the items that are present in both the sets.

Consider the following example to calculate the union of two sets.

Example 1: using union | operator

Days1 = {"Monday","Tuesday","Wednesday","Thursday", "Sunday"}


Days2 = {"Friday","Saturday","Sunday"}
print(Days1|Days2) #printing the union of the sets

Output:

{'Friday', 'Sunday', 'Saturday', 'Tuesday', 'Wednesday', 'Monday', 'Thursday'}

Python also provides the union() method which can also be used to calculate the union of two sets.
Consider the following example.

Example 2: using union() method


33

Days1 = {"Monday","Tuesday","Wednesday","Thursday"}
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

Days2 = {"Friday","Saturday","Sunday"}
print(Days1.union(Days2)) #printing the union of the sets

Output:

{'Friday', 'Monday', 'Tuesday', 'Thursday', 'Wednesday', 'Sunday', 'Saturday'}


Intersection of two sets

The intersection of two sets can be performed by the and & operator or the intersection() function.
The intersection of the two sets is given as the set of the elements that common in both sets.

Consider the following example.

Example 1: Using & operator

Days1 = {"Monday","Tuesday", "Wednesday", "Thursday"}


Days2 = {"Monday","Tuesday","Sunday", "Friday"}
print(Days1&Days2) #prints the intersection of the two sets

Output:

{'Monday', 'Tuesday'}

Example 2: Using intersection() method

set1 = {"Devansh","John", "David", "Martin"}


set2 = {"Steve", "Milan", "David", "Martin"}
34

print(set1.intersection(set2)) #prints the intersection of the two sets


Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

Output:

{'Martin', 'David'}

Example 3:

set1 = {1,2,3,4,5,6,7}
set2 = {1,2,20,32,5,9}
set3 = set1.intersection(set2)
print(set3)

Output:

{1,2,5}

Python Built-in set methods

Python contains the following methods to be used with the sets.

SN Method Description

1 add(item) It adds an item to the set. It has no effect if the item is already
present in the set.

2 clear() It deletes all the items from the set.

3 copy() It returns a shallow copy of the set.

4 difference_update(....) It modifies this set by removing all the items that are also
present in the specified sets.

5 discard(item) It removes the specified item from the set.

6 intersection() It returns a new set that contains only the common elements of
both the sets. (all the sets if more than two are specified).

7 intersection_update(....) It removes the items from the original set that are not present
35
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

in both the sets (all the sets if more than one are specified).

8 Isdisjoint(....) Return True if two sets have a null intersection.

9 Issubset(....) Report whether another set contains this set.

10 Issuperset(....) Report whether this set contains another set.

11 pop() Remove and return an arbitrary set element that is the last
element of the set. Raises KeyError if the set is empty.

12 remove(item) Remove an element from a set; it must be a member. If the


element is not a member, raise a KeyError.

13 symmetric_difference(....) Remove an element from a set; it must be a member. If the


element is not a member, raise a KeyError.

14 symmetric_difference_update(....) Update a set with the symmetric difference of itself and


another.

15 union(....) Return the union of sets as a new set.


(i.e. all elements that are in either set.)

16 update() Update a set with the union of itself and others.


36
Page

You might also like