0% found this document useful (0 votes)
20 views160 pages

Unit Ii

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

Unit Ii

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

Ternary Operator

>>> a = 10
>>> b = 20
>>> c = a if a>b else b
>>> c
20
>>> print(a if a>b else b)
20

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Switch in Python
>>> a = 20
>>> b = (0 if a== 0 else
1 if a==1 else
2 if a==2 else 3)
>>> print(b)
3

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


UNIT II
• Working with Strings
• Lists and Tuples
• Dictionaries: When Indices Won’t Do
• Sets: set methods, set comprehensions.

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Working with Strings:

• Basic String Operations,


• String Formatting,
• String Methods.

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Common Sequence Operations

• There are certain things you can do with all sequence types.
• These operations include indexing, slicing, adding, multiplying, and
checking for membership.
• In addition, Python has built-in functions for finding the length of a
sequence and for finding its largest and smallest elements.

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Indexing
• All elements in a sequence are numbered—from zero and upward. You can
access them individually with a number, like this:
>>> greeting = 'Hello'
>>> greeting[0]
'H'

Note: A string is just a sequence of characters. The index 0 refers to the first
element, in this case the letter H. A character is just a single element string.

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


• You use an index to fetch an element. All sequences can be
indexed in this way.
• When you use a negative index, Python counts from the right,
that is, from the last element. The last element is at position –1.
>>> greeting[-1]
'o'

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Slicing
• Just as you use indexing to access individual elements, you can
use slicing to access ranges of elements.
• You do this by using two indices, separated by a colon.
>>> tag = '<a href="http://www.python.org">Python web site</a>'
>>> tag[9:30]
'http://www.python.org'
>>> tag[32:-4]
'Python web site'

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Adding
• Sequences can be concatenated with the addition (plus) operator.
>>> 'Hello,' + 'world!'
'Hello, world!’

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Multiplication
• Multiplying a sequence by a number x creates a new sequence
where the original sequence is repeated x times:
>>> 'python' * 5
'pythonpythonpythonpythonpython’

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Membership
• To check whether a value can be found in a sequence, you use the
in operator.
• This operator is a bit different from the ones discussed so far (such
as multiplication or addition).
>>> permissions = 'rw'
>>> 'w' in permissions
True
>>> 'x' in permissions
False
>>> subject = '$$$ Get rich now!!! $$$'
>>> '$$$' in subject
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
• Length, Minimum, and Maximum

>>> Name = 'Aditya'


>>> len(Name)
6
>>> min(Name)
'A'
>>> max(Name)
'y'
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Python String Methods
• Python String capitalize()
• In Python, the capitalize() method converts first character of a string to uppercase letter and
lowercases all other characters, if any.
• The syntax of capitalize() is:
• string.capitalize()
• capitalize() Parameter
• The capitalize() method doesn't take any parameter.
>>> name = "vinay"
>>> name.capitalize()
' Vinay '
>>> name = "vINAY"
>>> name.capitalize()
'Vinay'
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
• Return Value from capitalize()
• The capitalize() function returns a string with the first letter
capitalized and all other characters lowercased. It doesn't
modify the original string.

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


• Python String casefold()
• The casefold() method is an aggressive lower() method which converts
strings to case folded strings for caseless matching.
• The syntax of casefold() is:
• string.casefold()
• Parameters for casefold()
• The casefold() method doesn't take any parameters.
• Return value from casefold()
• The casefold() method returns the case folded string.
• The casefold() method removes all case distinctions present in a string. It is
used for caseless matching, i.e. ignores cases when comparing.
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
>>> a = 'vinay'
>>> a.casefold()
'vinay'
>>> a = 'VINAY'
>>> a.casefold()
'vinay‘
>>> name = "vINAY"
>>> name.capitalize()
'Vinay'
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Python String center()

• The center() method returns a string which is padded with the


specified character.
• The syntax of center() method is:
• string.center(width[, fillchar])center() Parameters
• The center() method takes two arguments:
• width - length of the string with padded characters
• fillchar (optional) - padding character
• The fillchar argument is optional. If it's not provided, space is
taken as default argument.
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
>>> name = 'vinay'
>>> name.center(20)
' vinay '
>>> name.center(20, '*')
'*******vinay********'

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Python String find()

• The find() method returns the index of first occurrence of the


substring (if found). If not found, it returns -1.
• The syntax of the find() method is:
• str.find(sub[, start[, end]] )Parameters for the find() method
• The find() method takes maximum of three parameters:
• sub - It is the substring to be searched in the str string.
• start and end (optional) - The range str[start:end] within which
substring is searched.

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


• Return Value from find() method
• The find() method returns an integer value:
• If the substring exists inside the string, it returns the index of
the first occurrence of the substring.
• If substring doesn't exist inside the string, it returns -1.

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Python String format()
• The string format() method formats the given string into a nicer
output in Python.
• The syntax of the format() method is:
template.format(p0, p1, ..., k0=v0, k1=v1, ...)
• Here, p0, p1,... are positional arguments and, k0, k1,... are keyword
arguments with values v0, v1,... respectively.
• And, template is a mixture of format codes with placeholders for
the arguments.

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


• format() method takes any number of parameters. But, is
divided into two types of parameters:
• Positional parameters - list of parameters that can be accessed
with index of parameter inside curly braces {index}
• Keyword parameters - list of parameters of type key=value,
that can be accessed with key of parameter inside curly
braces {key}
• Return value from String format()
• The format() method returns the formatted string.
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
# default arguments
>>> print("Hello {}, your balance is {}.".format("Adam", 230.2346))
# positional arguments
>>> print("Hello {0}, your balance is {1}.".format("Adam", 230.2346))
# keyword arguments
>>> print("Hello {name}, your balance is {blc}.".format(name="Adam",
blc=230.2346))
# mixed arguments
>>> print("Hello {0}, your balance is {blc}.".format("Adam",
blc=230.2346))
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Python String join()
• The join() string method returns a string by joining all the
elements of an iterable, separated by a string separator.
• The syntax of the join() method is:
string.join(iterable)
• Parameters for the join() method
• The join() method takes an iterable (objects capable of returning
its members one at a time) as its parameter.
• Some of the example of iterables are:
• Native data types - List, Tuple, String, Dictionary and Set.
• File objects and objects you define with an __iter__()
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
• Return Value from join() method
• The join() method returns a string created by joining the elements of an iterable
by string separator.
Example:
>>> s1 = 'abc'
>>> s2 = '123'
# each element of s2 is separated by s1
# '1'+ 'abc'+ '2'+ 'abc'+ '3'
>>> print('s1.join(s2):', s1.join(s2))
# each element of s1 is separated by s2
# 'a'+ '123'+ 'b'+ '123'+ 'b'
print('s2.join(s1):',
Python Programming
s2.join(s1)) Nssv Prasad Kavitapu Sunday, November 24, 2024
Python String zfill()
• The zfill() method returns a copy of the string with '0' characters padded to the left.
• The syntax of zfill() in Python is:
str.zfill(width)
zfill() Parameter
• zfill() takes a single character width.
• The width specifies the length of the returned string from zfill() with 0 digits filled to the left.
• Return Value from zfill()
• zfill() returns a copy of the string with 0 filled to the left. The length of the returned string
depends on the width provided.
• Suppose, the initial length of the string is 10. And, the width is specified 15. In this
case, zfill() returns a copy of the string with five '0' digits filled to the left.
• Suppose, the initial length of the string is 10. And, the width is specified 8. In this
case, zfill() doesn't fill '0' digits to the left and returns a copy of the original string. The
length of the returned string in this case will be 10.
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
• Example 1: How zfill() works in Python?
>>> text = "program is fun"
>>> print(text.zfill(15))
>>> print(text.zfill(20))
>>> print(text.zfill(10))

• Output
0program is fun
000000program is fun
program is fun
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Python String split()
• The split() method breaks up a string at the specified separator and returns a list
of strings.
• The syntax of split() is:
str.split([separator [, maxsplit]])
• split() Parameters
• split() method takes a maximum of 2 parameters:
• separator (optional)- It is a delimiter. The string splits at the specified separator.
If the separator is not specified, any whitespace (space, newline etc.) string is a
separator.
• maxsplit (optional) - The maxsplit defines the maximum number of splits.
The default value of maxsplit is -1, meaning, no limit on the number of splits.
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
• Return Value from split()
• split() breaks the string at the separator and returns a list of strings.
>>> text= 'Love thy neighbor'
# splits at space
>>> print(text.split())

Output
['Love', 'thy', 'neighbor']

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Example 2: How split() works when maxsplit is specified?

>>> grocery = 'Milk, Chicken, Bread, Butter'


# maxsplit: 2
>>> print(grocery.split(', ', 2))
Output
['Milk', 'Chicken', 'Bread, Butter']

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Python String rsplit()
• The rsplit() method splits string from the right at the specified
separator and returns a list of strings.
• The syntax of rsplit() is:
str.rsplit([separator [, maxsplit]])
• rsplit() Parameters
• rsplit() method takes maximum of 2 parameters:
• separator (optional)- The is a delimiter. rsplit() method splits
string starting from the right at the specified separator.
If the separator is not specified, any whitespace (space, newline
etc.) string is a separator.
• maxsplit (optional) - The maxsplit defines the maximum number
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
• Return Value from rsplit()
• rsplit() breaks the string at the separator starting from the right and returns a list of
strings.
• Example 1: How rsplit() works in Python?
>>> text= 'Love thy neighbor‘
• Output:
['Love', 'thy', 'neighbor']
Example 2: How split() works when maxsplit is specified?
>>> grocery = 'Milk, Chicken, Bread, Butter' # maxsplit: 2 print(grocery.rsplit(', ', 2))
• Output
['Milk, Chicken', 'Bread', 'Butter‘]
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Python String partition()
• The partition() method splits the string at the first occurrence of the argument string
and returns a tuple containing the part the before separator, argument string and the
part after the separator.
• The syntax of partition() is:
• string.partition(separator)
• partition() Parameters()
• The partition() method takes a string parameter separator that separates the string at
the first occurrence of it.
• Return Value from partition()
• The partition method returns a 3-tuple containing:
• the part before the separator, separator parameter, and the part after the separator if the
separator parameter is found in the string
• the string itself and two empty strings if the separator parameter is not found
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
• Example: How partition() works?
>>> string = "Python is fun"
# 'is' separator is found
>>> print(string.partition('is '))

Output
('Python ', 'is ', 'fun')

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Python String rpartition()
• The rpartition() splits the string at the last occurrence of the argument string and returns
a tuple containing the part the before separator, argument string and the part after the
separator.
• The syntax of rpartition() is:
• string.rpartition(separator)
• rpartition() Parameters()
• rpartition() method takes a string parameter separator that separates the string at the last
occurrence of it.
• Return Value from rpartition()
• rpartition() method returns a 3-tuple containing:
• the part before the separator, separator parameter, and the part after the separator if the
separator parameter is found in the string
• Python
two Programming
empty strings, followed by the string itself if the separator parameter is not found
Nssv Prasad Kavitapu Sunday, November 24, 2024
• Example: How rpartition() works?
>>> string = "Python is fun"
# 'is' separator is found
>>> print(string.rpartition('is '))
• Output
('Python ', 'is ', 'fun')

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Python String splitlines()
• The splitlines() method splits the string at line breaks and returns a
list of lines in the string.
• The syntax of splitlines() is:
• str.splitlines([keepends])
• splitlines() Parameters
• splitlines() takes maximum of 1 parameter.
• keepends (optional) - If keepends is provided and True, line breaks
are also included in items of the list.
• By default, the line breaks are not included.
• The syntax of splitlines() is:
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
• Return Value from splitlines()
• splitlines() returns a list of lines in the string.
• If there are not line break characters, it returns a list with a
single item (a single line).

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


List

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Introduction
• Python offers a range of compound data types often referred to as
sequences. List is one of the most frequently used and very versatile
data types used in Python.
• The list is the most versatile datatype available in Python, which
can be written as a list of comma-separated values (items) between
square brackets.
• Important thing about a list is that the items in a list need not be of
the same type.
• List is a collection which is ordered and changeable. Allows
duplicate members.
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
How to create a list?
• In Python programming, a list is created by placing all the items
(elements) inside square brackets [], separated by commas.
• It can have any number of items and they may be of different types
(integer, float, string etc.).
# empty list
>>> my_list = []
# list of integers
>>> my_list = [1, 2, 3]
# list with mixed data types
>>> my_list = [1, "Hello", 3.4]
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
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']]

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


How to access elements from a list?

• 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.
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
# Nested List
>>> n_list = ["Happy", [2, 0, 1, 5]]
# Nested indexing
>>> print(n_list[0][1])
>>> print(n_list[1][3])

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Python List Methods
• Python has some list methods that you can use to perform
frequency occurring task (related to list) with ease.
• For example, if you want to add element to a list, you can
use append() method.
• The page contains all methods of list objects. Also, the page
includes built-in functions that can take list as a parameter and
perform some task.
• For example, all() function returns True if all elements of an list
(iterable) is true.
• If not, it returns False.
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Method Description
Python List append() Add a single element to the end of the list
Python List extend() Add Elements of a List to Another List
Python List insert() Inserts Element to The List at particular index
Python List remove() Removes item from the list
Python List index() returns smallest index of element in list
Python List count() returns occurrences of element in a list
Python List pop() Removes element at the given index
Python List reverse() Reverses a List
Python List sort() sorts elements of a list
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Method Description
Python List copy() Returns Shallow Copy of a List
Python List clear() Removes all Items from the List
Python any() Checks if any Element of an Iterable is True
Python all() returns true when all elements in iterable is true
Python ascii() Returns String Containing Printable Representation
Python bool() Converts a Value to Boolean
Python enumerate() Returns an Enumerate Object
Python filter() constructs iterator from elements which are true
Python iter() returns iterator for an object
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Method Description
Python list() Function creates list in Python
Python len() Returns Length of an Object
Python max() returns largest element
Python min() returns smallest element
Python map() Applies Function and Returns a List
Python reversed() returns reversed iterator of a sequence
Python slice() creates a slice object specified by range()
Python sorted() returns sorted list from a given iterable
Python sum() Add items of an Iterable
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
• Insertion order preserves
• Duplicate objects are allowed
• Heterogeneous objects are allowed
• Dynamic (shrinkable and growable)
• Mutable
• Indexing and slicing are applicable
• Lists are represented by using []
• L = [ True, 2, 3.45, “vinay”, b”vinay”, 3+6j, [1,2], (3,4),
{1,2,3}, {1:2, 2:3, 3:4}]
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Python List append()
• The append() method adds an item to the end of the list.
• The syntax of the append() method is:
list.append(item)
• append() Parameters
• The method takes a single argument
• item - an item to be added at the end of the list
• The item can be numbers, strings, dictionaries, another list, and so
on.
• Return Value from append()
• The method doesn't return any value (returns None).
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Example 1: Adding Element to a List

• # animals list
>>> animals = ['cat', 'dog', 'rabbit']
# 'guinea pig' is appended to the animals list
>>> animals.append(‘pig')
# Updated animals list
>>> print('Updated animals list: ', animals)
• Output
Updated animals list: ['cat', 'dog', 'rabbit', 'pig']
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Python List extend()
• The extend() method adds all the elements of an iterable (list, tuple,
string etc.) to the end of the list.
• The syntax of the extend() method is:
list1.extend(iterable)
• Here, all the elements of iterable are added to the end of list1.
• extend() Parameters
• As mentioned, the extend() method takes an iterable such as list, tuple,
string etc.
• Return Value from extend()
• The extend() method modifies the original list. It doesn't return any
value.
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Example 1: Using extend() Method
# language list
>>> language = ['French', 'English']
# another list of language
>>> language1 = ['Spanish', 'Portuguese']
# appending language1 elements to language
>>> language.extend(language1)
>>> print('Language List:', language)
Output
Language List: ['French', 'English', 'Spanish', 'Portuguese']
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Python List insert()
• Python List insert()
• The list insert() method inserts an element to the list at the
specified index.
• The syntax of the insert() method is
list.insert(i, elem)
• Here, elem is inserted to the list at the i th index. All the elements
after elem are shifted to the right.
• insert() Parameters
• The insert() method takes two parameters:
• index - the index where the element needs to be inserted
• element - this is the element to be inserted in the list
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
• Notes:
• If index is 0, the element is inserted at the beginning of the list.
• If index is 3, the element is inserted after the 3rd element. Its
position will be 4th.
• Return Value from insert()
• The insert() method doesn't return anything; returns None. It only
updates the current list.

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Example 1: Inserting an Element to the List
# vowel list
>>> vowel = ['a', 'e', 'i', 'u']
# 'o' is inserted at index 3 # the position of 'o' will be 4th
>>> vowel.insert(3, 'o')
>>> print('Updated List:', vowel)
Output
Updated List: ['a', 'e', 'i', 'o', 'u']

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Python List remove()
• The remove() method removes the first matching element (which is passed
as an argument) from the list.
• The syntax of the remove() method is:
list.remove(element)
• remove() Parameters
• The remove() method takes a single element as an argument and removes
it from the list.
• If the element doesn't exist, it throws ValueError: list.remove(x): x not
in list exception.
• Return Value from remove()
• The remove() doesn't return any value (returns None).
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Example 1: Remove element from the list
# animals list
>>> animals = ['cat', 'dog', 'rabbit', ‘pig']
# 'rabbit' is removed
>>> animals.remove('rabbit')
# Updated animals List
>>> print('Updated animals list: ', animals)
Output
Updated animals list: ['cat', 'dog', ‘pig']
• If you need to delete elements based on the index (like the fourth element),
you can use the pop() method.
• Also, you can use the Python del statement to remove items from the list.
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Python List pop()
• The pop() method removes the item at the given index from the list and returns the
removed item.
• The syntax of the pop() method is:
list.pop(index)
• pop() parameters
• The pop() method takes a single argument (index).
• The argument passed to the method is optional. If not passed, the default index -1 is
passed as an argument (index of the last item).
• If the index passed to the method is not in range, it throws IndexError: pop index
out of range exception.
• Return Value from pop()
• The pop() method returns the item present at the given index. This item is also
removed from the list.
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Example 1: Pop item at the given index from the list
# programming languages list
>>> languages = ['Python', 'Java', 'C++', 'French', 'C']
# remove and return the 4th item
>>> return_value = languages.pop(3)
>>> print('Return Value:', return_value)
# Updated List print('Updated List:', languages)
Output
Return Value: French Updated List: ['Python', 'Java', 'C++', 'C']

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Python List clear()
• The clear() method removes all items from the list.
• The syntax of clear() method is:
list.clear()
• clear() Parameters
• The clear() method doesn't take any parameters.
• Return Value from clear()
• The clear() method only empties the given list. It doesn't return any
value.

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Example 1: Working of clear() method

# Defining a list
>>> list = [{1, 2}, ('a'), ['1.1', '2.2']]
# clearing the list
>>> list.clear()
>>> print('List:', list)
Output
List: []

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Python List reverse()
• The reverse() method reverses the elements of the list.
• The syntax of the reverse() method is:
list.reverse()
• reverse() parameter
• The reverse() method doesn't take any arguments.
• Return Value from reverse()
• The reverse() method doesn't return any value. It updates the
existing list.

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Example 1: Reverse a List
# Operating System List
>>> systems = ['Windows', 'macOS', 'Linux']
>>> print('Original List:', systems)
# List Reverse
>>> systems.reverse()
# updated list
>>> print('Updated List:', systems)
Output
Original List: ['Windows', 'macOS', 'Linux']
Updated List: ['Linux', 'macOS', 'Windows']
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Example 2: Reverse a List Using Slicing Operator
# Operating System List
>>> systems = ['Windows', 'macOS', 'Linux']
>>> print('Original List:', systems)
# Reversing a list
#Syntax: reversed_list = systems[start:stop:step]
>>> reversed_list = systems[::-1]
# updated list
>>> print('Updated List:', reversed_list)
Output
Original List: ['Windows', 'macOS', 'Linux']
Updated List: ['Linux', 'macOS',
Python Programming
'Windows']
Nssv Prasad Kavitapu Sunday, November 24, 2024
Example 3: Accessing Elements in Reversed Order

• If you need to access individual elements of a list in the reverse


order, it's better to use reversed() function.
# Operating System List
>>> systems = ['Windows', 'macOS', 'Linux']
# Printing Elements in Reversed Order
>>> for o in reversed(systems): print(o)
Output
Linux macOS Windows

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Python List sort()
• The sort() method sorts the elements of a given list in a specific ascending
or descending order.
• The syntax of the sort() method is:
list.sort(key=..., reverse=...)
• Alternatively, you can also use Python's built-in sorted() function for the
same purpose.
• sorted(list, key=..., reverse=...)
• Note: The simplest difference between sort() and sorted() is:
• sort() changes the list directly and doesn't return any value,
while sorted() doesn't change the list and returns the sorted list.

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


• sort() Parameters
• By default, sort() doesn't require any extra parameters. However, it
has two optional parameters:
• reverse - If True, the sorted list is reversed (or sorted in
Descending order)
• key - function that serves as a key for the sort comparison
• Return value from sort()
• The sort() method doesn't return any value. Rather, it changes the
original list.
• If you want a function to return the sorted list rather than change
the original list, use sorted().
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Example 1: Sort a given list

# vowels list
>>> vowels = ['e', 'a', 'u', 'o', 'i']
# sort the vowels
>>> vowels.sort()
# print vowels
>>> print('Sorted list:', vowels)
Output
Sorted list: ['a', 'e', 'i', 'o', 'u']
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Example 2: Sort the list in Descending order
# vowels list
>>> vowels = ['e', 'a', 'u', 'o', 'i']
# sort the vowels
>>> vowels.sort(reverse=True)
# print vowels
>>> print('Sorted list (in Descending):', vowels)
Output
Sorted list (in Descending): ['u', 'o', 'i', 'e', 'a']

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


• Sort with custom function using key
• If you want your own implementation for sorting, the sort() method also
accepts a key function as an optional parameter.
• Based on the results of the key function, you can sort the given list.
list.sort(key=len)
• Alternatively for sorted:
sorted(list, key=len)
• Here, len is the Python's in-built function to count the length of an element.
• The list is sorted based on the length of each element, from lowest count to
highest.
• We know that a tuple is sorted using its first parameter by default. Let's look at
how to customize the sort() method to sort using the second element.
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Example 3: Sort the list using key

>>> l = ['as', 'asd', 'a']


>>> l.sort(key = len)
>>> l
['a', 'as', 'asd']

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Python List count()
• The count() method returns the number of times the specified
element appears in the list.
• The syntax of the count() method is:
list.count(element)
• count() Parameters
• The count() method takes a single argument:
• element - the element to be counted
• Return value from count()
• The count() method returns the number of times element appears
in the list.
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Example 1: Use of count()
# vowels list
>>> vowels = ['a', 'e', 'i', 'o', 'i', 'u']
# count element 'i'
count = vowels.count('i')
# print count
>>> print('The count of i is:', count)
# count element 'p'
>>> count = vowels.count('p')
# print count
>>> print('The count of p is:', count)
Output
The count of i is: 2
The count of p is: 0
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Python List copy()
• The copy() method returns a shallow copy of the list.
• A list can be copied using the = operator. For example,
>>> old_list = [1, 2, 3] ​
>>> new_list = old_list
• The problem with copying lists in this way is that if you
modify new_list, old_list is also modified.

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Python List index()
• The index() method returns the index of the specified element in the list.
• The syntax of the list index() method is:
list.index(element, start, end)
• list index() parameters
• The list index() method can take a maximum of three arguments:
• element - the element to be searched
• start (optional) - start searching from this index
• end (optional) - search the element up to this index
• Return Value from List index()
• The index() method returns the index of the given element in the list.
• If the element is not found, a ValueError exception is raised.
• Note: The index() method only returns the first occurrence of the matching element.
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Example 1: Find the index of the element
# vowels list
>>> vowels = ['a', 'e', 'i', 'o', 'i', 'u']
# index of 'e' in vowels
>>> index = vowels.index('e')
>>> print('The index of e:', index)
# element 'i' is searched
# index of the first 'i' is returned
>>> index = vowels.index('i')
>>> print('The index of i:', index)
Output
The index of e: 1
ThePython
index of i: 2
Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Example 2: Index of the Element not Present in the List
# vowels list
>>> vowels = ['a', 'e', 'i', 'o', 'u']
# index of'p' is vowels
>>> index = vowels.index('p')
>>> print('The index of p:', index)
• Output
ValueError: 'p' is not in list

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Example 3: Working of index() With Start and End Parameters
# alphabets list
>>> alphabets = ['a', 'e', 'i', 'o', 'g', 'l', 'i', 'u']
# index of 'i' in alphabets
>>> index = alphabets.index('e') # 2
>>> print('The index of e:', index)
# 'i' after the 4th index is searched
>>> index = alphabets.index('i', 4) # 6
>>> print('The index of i:', index) # 'i' between 3rd and 5th index is searched
>>> index = alphabets.index('i', 3, 5) # Error!
>>> print('The index of i:', index)
Output
The index of e: 1
The index of i: 6
Traceback (most recent call last): File Nssv
Python Programming "*lt;string>",
Prasad Kavitapu line 13, in ValueError: 'i'Sunday,
is not in list
November 24, 2024
TUPLE

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Python Tuple: Immutable Sequences
• A tuple in Python is similar to a list.
• Tuples are sequences, just like lists.
• The only difference is that tuples can’t be changed.
• The tuple syntax is simple—if you separate some values with commas, you
automatically have a tuple.
>>> 1, 2, 3
(1, 2, 3)
• As you can see, tuples may also be (and often are) enclosed in parentheses.
>>> (1, 2, 3)
(1, 2, 3)
• The empty tuple is written as two parentheses containing nothing.
>>> ()
()
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
• So, you may wonder how to write a tuple containing a single
value.
• This is a bit peculiar—you have to include a comma, even
though there is only one value.
>>> 42
42
>>> 42,
(42,)
>>> (42,)
(42,)
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
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
>>> my_tuple = () # Empty tuple
>>> print(my_tuple) # Tuple having integers
>>> my_tuple = (1, 2, 3)
>>> print(my_tuple)
>>> my_tuple = (1, "Hello", 3.4) # tuple with mixed datatypes
>>> print(my_tuple)
>>> my_tuple = ("mouse", [8, 4, 6], (1, 2, 3)) # nested tuple
>>> print(my_tuple)
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
• Output
() (1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Packing, unpacking
• A tuple can also be created without using parentheses. This is known as tuple
packing.
>>> my_tuple = 3, 4.6, "dog"
>>> print(my_tuple) # tuple unpacking is also possible
>>> a, b, c = my_tuple
>>> print(a) # 3
>>> print(b) # 4.6
>>> print(c) # dog
• Output
(3, 4.6, 'dog')
3
4.6
dogPython Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
>>> tuple([1, 2, 3])
(1, 2, 3)
>>> tuple('abc')
('a', 'b', 'c')
>>> tuple((1, 2, 3))
(1, 2, 3)

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Access Tuple Elements
• Access Tuple Elements
• There are various ways in which we can access the elements of a
tuple.
• 1. Indexing
• We can use the index operator [] to access an item in a tuple, where
the index starts from 0.
• So, a tuple having 6 elements will have indices from 0 to 5. Trying to
access an index outside of the tuple index range(6,7,... in this
example) will raise an IndexError.
• The index must be an integer, so we cannot use float or other types.
This will result in TypeError.
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Likewise, nested tuples are accessed using nested indexing, as
shown in the example below.

# nested tuple
>>> n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
# nested index
>>> print(n_tuple[0][3]) # 's'
>>> print(n_tuple[1][1]) #4
• Output
s
4
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
• 2. Negative Indexing
• 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.
# Negative indexing for accessing tuple elements
>>> my_tuple = ('p', 'e', 'r', 'm', 'i', 't')
>>> print(my_tuple[-1]) # Output: 't'
>>> print(my_tuple[-6]) # Output: 'p'
• Output
t Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
3. Slicing
• We can access a range of items in a tuple by using the slicing operator
colon :.
# Accessing tuple elements using slicing
>>> my_tuple = ('p','r','o','g','r','a','m','i','z')
>>> print(my_tuple[1:4]) # elements 2nd to 4th # Output: ('r', 'o', 'g')
# elements beginning to 2nd
>>> print(my_tuple[:-7]) # Output: ('p', 'r')
# elements 8th to end
>>> print(my_tuple[7:]) # Output: ('i', 'z')
# elements beginning to end
>>> print(my_tuple[:]) # Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Changing a Tuple
• Unlike lists, tuples are immutable.
• This means that elements of a tuple cannot be changed once they have been
assigned. But, if the element is itself a mutable data type like list, its nested
items can be changed.
• We can also assign a tuple to different values (reassignment).
# Changing tuple values
>>> my_tuple = (4, 2, 3, [6, 5])
# TypeError: 'tuple' object does not support item assignment
# my_tuple[1] = 9
# However, item of mutable element can be changed
>>> my_tuple[3][0] = 9
>>> print(my_tuple) # Output: (4, 2, 3, [9, 5])
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
• We can use + operator to combine two tuples. This is
called concatenation.
• We can also repeat the elements in a tuple for a given number of
times using the * operator.
• Both + and * operations result in a new tuple.
# Concatenation
>>> print((1, 2, 3) + (4, 5, 6)) # Output: (1, 2, 3, 4, 5, 6)
# Repeat
>>> print(("Repeat",) * 3) # Output: ('Repeat', 'Repeat', 'Repeat')
Output
(1, 2, 3, 4, 5, 6)
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Deleting a Tuple
• we cannot delete or remove items from a tuple.
• Deleting a tuple entirely, however, is possible using the keyword del.
# Deleting tuples
>>> my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
>>> del my_tuple
# NameError: name 'my_tuple' is not defined
>>> print(my_tuple)
• Output
Traceback (most recent call last): File "<string>", line 12, in <module>
NameError: name 'my_tuple' is not defined
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Tuple Methods

• count
• index

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Python Tuple count()
• The count() method returns the number of times the specified
element appears in the tuple.
• The syntax of the count() method is:
• tuple.count(element)
• count() Parameters
• The count() method takes a single argument:
• element - the element to be counted
• Return value from count()
• The count() method returns the number of times element appears in
the tuple.
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Example 1: Use of Tuple count()
# vowels tuple
>>> vowels = ('a', 'e', 'i', 'o', 'i', 'u') # count element 'i'
>>> count = vowels.count('i') # print count
>>> print('The count of i is:', count) # count element 'p'
>>> count = vowels.count('p') # print count
>>> print('The count of p is:', count)
Output
The count of i is: 2
The count of p is: 0
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Python Tuple index()
• The index() method returns the index of the specified element in the tuple.
• The syntax of the tuple index() method is:
tuple.index(element, start, end)
• Tuple index() parameters
• The tuple index() method can take a maximum of three arguments:
• element - the element to be searched
• start (optional) - start searching from this index
• end (optional) - search the element up to this index
• Return Value from Tuple index()
• The index() method returns the index of the given element in the tuple.
• If the element is not found, a ValueError exception is raised.
• Note: The index() method only returns the first occurrence of the matching element.
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Example 1: Find the index of the element
# vowels tuple
>>> vowels = ('a', 'e', 'i', 'o', 'i', 'u')
>>> index = vowels.index('e') # index of 'e' in vowels
>>> print('The index of e:', index)
# element 'i' is searched
>>> index = vowels.index('i') # index of the first 'i' is returned
>>> print('The index of i:', index)
Output
The index of e: 1
The index of e: 2
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
• Advantages of Tuple over List
• Since tuples are quite similar to lists, both of them are used in similar situations.
However, there are certain advantages of implementing a tuple over a list. Below
listed are some of the main advantages:
• We generally use tuples for heterogeneous (different) data types and lists for
homogeneous (similar) data types.
• Since tuples are immutable, iterating through a tuple is faster than with list. So
there is a slight performance boost.
• Tuples that contain immutable elements can be used as a key for a dictionary. With
lists, this is not possible.
• If you have data that doesn't change, implementing it as tuple will guarantee that
it remains write-protected.
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Python Sets
• You'll learn everything about Python sets; how they are
created, adding or removing elements from them, and all
operations performed on sets in Python.

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


• A set is an unordered collection of items.
• This is based on a data structure known as a hash table.
• Every set element is unique (no duplicates) and must be immutable
(cannot be changed).
• However, a set itself is mutable.
• We can add or remove items from it.
• Sets can also be used to perform mathematical set operations like
union, intersection, symmetric difference, etc.

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Contents
• What is a set in Python?
• How to create a set?
• How to change a set in Python?
• How to remove elements from a set?
• Python Set Operations
Set Union
Set Intersection
Set Difference
Set Symmetric Difference
• Different Python Set Methods
Set Membership Test
Iterating through a Set
Built-in Functions with Set
• Python Frozenset
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Creating Python Sets
• A set is created by placing all the items (elements) inside curly braces {}, separated by comma,
or by using the built-in set() function.
• It can have any number of items and they may be of different types (integer, float, tuple, string
etc.).
• But a set cannot have mutable elements like lists, sets or dictionaries as its elements.
• # Different types of sets in Python
>>> my_set = set() # Empty set
>>> my_set = {1, 2, 3} # set of integers
>>> print(my_set)
>>> my_set = {1.0, "Hello", (1, 2, 3)} # set of mixed datatypes
>>> print(my_set)
• Output
{1, 2, 3}
{1.0,Python
(1,Programming
2, 3), 'Hello'} Nssv Prasad Kavitapu Sunday, November 24, 2024
Creating an empty set is a bit tricky.
• Empty curly braces {} will make an empty dictionary in Python. To make a
set without any elements, we use the set() function without any argument.
• # Distinguish set and dictionary while creating empty set initialize a with {}
>>> a = {} # check data type of a
>>> print(type(a)) # initialize a with set()
>>> a = set() # check data type of a
print(type(a))
Output
<class 'dict'>
<class 'set'>

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Modifying a set in Python
• Sets are mutable.
• However, since they are unordered, indexing has no meaning.
• We cannot access or change an element of a set using indexing
or slicing. Set data type does not support it.
• We can add a single element using the add() method, and
multiple elements using the update() method.
• The update() method can take tuples, lists, strings or other sets
as its argument.
• In all cases, duplicates are avoided.

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


>>> my_setmy_set = {1,3} # initialize
>>> print(my_set)
# if you uncomment below line, you will get an error TypeError: 'set'
object does not support indexing
>>> my_set[0] # Error
>>> my_set.add(2) # add an element
>>> print(my_set)
>>> my_set.update([2,3,4]) # add multiple elements
>>> print(my_set) # add list and set
# Output: {1, 2, 3, 4, 5, 6, 8}
>>> my_set.update([4,5], {1,6,8})
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
How to remove elements from a set?
discard(), remove(), pop() and clear()
• A particular item can be removed from set using
methods, discard() and remove().
• The only difference between the two is that, while
using discard() if the item does not exist in the set, it remains
unchanged. But remove() will raise an error in such condition.

• The following example will illustrate this.

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


# initialize
>>> my_setmy_set = {1, 3, 4, 5, 6}
>>> print(my_set)
# discard an element
>>> my_set.discard(4)
>>> print(my_set) # Output: {1, 3, 5, 6}
# remove an element
>>> my_set.remove(6)
>>> print(my_set) # Output: {1, 3, 5}
>>> my_set.discard(2) # discard an element not present in my_set
>>> print(my_set) # Output: {1, 3, 5}
# remove an element not present in my_set
# If you uncomment below line, you will get an error
>>> # my_set.remove(2) # Output:
Python Programming
KeyError:
Nssv Prasad Kavitapu Sunday, November 24, 2024
• Similarly, we can remove and return an item using
the pop() method.
• Set being unordered, there is no way of determining which item
will be popped. It is completely arbitrary.
• We can also remove all items from a set using clear().
• There are two methods to remove an element from a
set: discard and remove. Their behavior varies only in case if the
deleted item was not in the set. In this case the
method discard does nothing and the method remove throws
exception KeyError.
• Finally, pop removes one random element from the set and returns
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Removing elements from a set

• Set Union

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Python Set Operations

Set Union
Set Intersection
Intersection_update
Set Difference
Difference_update
Set Symmetric Difference
Symmetric_difference_update

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Set Union (|)
• Union of A and B is a set of all elements from both sets.
• Union is performed using | operator. Same can be accomplished using the
method union().
• # initialize A and B
>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}
# use | operator
>>> print(A | B) # Output: {1, 2, 3, 4, 5, 6, 7, 8}
# use union function
>>> A.union(B) # {1, 2, 3, 4, 5, 6, 7, 8}
# use union function on B
>>> B.union(A) # {1, 2, 3, 4,Nssv5,Prasad
Python Programming 6, Kavitapu
7, 8} Sunday, November 24, 2024
Set Intersection (&)
• Intersection of A and B is a set of elements that are common in both sets.
• Intersection is performed using & operator. Same can be accomplished using
the method intersection().
• # initialize A and B
>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}
# use & operator
>>> print(A & B)
Output:
{4, 5}
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}
# use intersection function on A
>>> A.intersection(B)
{4, 5}
# use intersection function on B
>>> B.intersection(A)
{4, 5}
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Set intersection_update()
• The intersection_update() updates the set calling intersection_update()
method with the intersection of sets.
• The intersection of two or more sets is the set of elements which are
common to all sets.
• The syntax of intersection_update() is:
• A.intersection_update(*other_sets)
• intersection_update() Parameters
• The intersection_update() allows arbitrary number of arguments (sets).
• Note: * is not part of the syntax. It is used to indicate that the method
allows arbitrary number of arguments.
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Return Value from Intersection_update()
• This method returns None (meaning, absence of a return value). It only
updates the set calling the intersection_update() method.
• Suppose,
• result = A.intersection_update(B, C)
• When you run the code,
• result will be None
• A will be equal to the intersection of A, B and C
• B remains unchanged
• C remains unchanged
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
• A = {1, 2, 3, 4}
• B = {2, 3, 4, 5}

• result = A.intersection_update(B)

• print('result =', result)


• print('A =', A)
• print('B =', B)
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Set Symmetric Difference (^)
• Symmetric Difference of A and B is a set of elements in
both A and B except those that are common in both.
• Symmetric difference is performed using ^ operator. Same can
be accomplished using the method symmetric_difference().
# initialize A and B
>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}
# use ^ operator
>>> print(A ^ B) # Output: {1, 2, 3, 6, 7, 8}
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
• The symmetric_difference() returns a new set which is the
symmetric difference of two sets.
• The symmetric difference of two sets A and B is the set of
elements which are in either of the sets A or B but not in both.
• The syntax of symmetric_difference() is:
• C = A.symmetric_difference(B)

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


• symmetric_difference() Parameters
• The symmetric_difference takes a single argument (set).
• Return Value from symmetric_difference()
• The symmetric_difference() returns a new set which is the symmetric
difference of sets A and B.
• Example 1: How symmetric_difference() works in Python?
• A = {'a', 'b', 'c', 'd'}
• B = {'c', 'd', 'e' }
• C = {} # can be any collection list, tuple, set, dict, str
• print(A.symmetric_difference(B))
• print(B.symmetric_difference(A))
• print(A.symmetric_difference(C))
• print(B.symmetric_difference(C))
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Python Set isdisjoint()
• The isdisjoint() method returns True if two sets are disjoint sets. If not,
it returns False.
• Two sets are said to be disjoint sets if they have no common elements.
• For example:
• A = {1, 5, 9, 0}
• B = {2, 4, -5}
• Here, sets A and B are disjoint sets.

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Python Dictionary
• https://realpython.com/courses/diction
aries-python/
• https://www.programiz.com/python-pro
gramming/dictionary
Python Programming Nssv Prasad https://www.programiz.com/python-pro
• Kavitapu Sunday, November 24, 2024
gramming/nested-dictionary
Introduction
• Python dictionary is an unordered collection of items.
• Dictionary are mutable.
• While other compound data types have only value as an
element, a dictionary has a key: value pair.
• Dictionaries are optimized to retrieve values when the key is
known.

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


How to create a dictionary?
• Creating a dictionary is as simple as placing items inside curly
braces {} separated by comma.
• An item has a key and the corresponding value expressed as a pair,
key: value.
• While values can be of any data type and can repeat, keys must be
of immutable type (bool, complex, string, number, float or tuple
with immutable elements) and must be unique.

• Note: set, list, and dict are not allowed as keys bcz they are
unhashable and mutable.
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
• # empty dictionary
• my_dict = {}
• my_dict = dict()
• # dictionary with integer keys
• my_dict = {1: 'apple', 2: 'ball'}
• # dictionary with mixed keys
• my_dict = {'name': 'John', 1: [2, 4, 3]}
• # using dict()
• my_dict = dict({1:'apple', 2:'ball'})
• # from sequence having each item as a pair
• my_dict = dict([(1,'apple'), (2,'ball')])
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
How to access elements from a
dictionary?
• While indexing is used with other container types to access values,
dictionary uses keys.
• Key can be used either inside square brackets or with
the get() method.
• The difference while using get() is that it returns None instead
of KeyError, if the key is not found.

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


• my_dict = {'name':'Jack', 'age': 26}
• print(my_dict['name'])
• # Output: Jack
• print(my_dict.get('age'))
• # Output: 26
• # Trying to access keys which doesn't exist throws error
• # my_dict.get('address')
• # my_dict['address']
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
How to change or add elements in a
dictionary?
• Dictionary are mutable.
• We can add new items or change the value of existing items using
assignment operator.
• If the key is already present, value gets updated, else a new key: value pair
is added to the dictionary.

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


• my_dict = {'name':'Jack', 'age': 26}

• # update value
• my_dict['age'] = 27
• print(my_dict)
• #Output: {'age': 27, 'name': 'Jack'}

• # add item
• my_dict['address'] = 'Downtown'
• print(my_dict)
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
• # Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}
Python List Comprehension
• Learn how to effectively use list comprehension in Python to create lists, to
replace (nested) for loops and the map(), filter() and reduce() functions, ...!
• List comprehension in Python is also surrounded by brackets, but instead of the
list of data inside it, you enter an expression followed by for loop and if-
else clauses.
• list_variable = [expression for item in collection/iterable]
• new_list = [expression for member in iterable (if conditional)]
• The first expression generates elements in the list followed by a for loop over
some collection of data which would evaluate the expression for every item in
the collection.
• S = [x**2 for x in range(10)]
• V Python
= [2**i for i in range(13)] Nssv Prasad Kavitapu
Programming Sunday, November 24, 2024
Example 1:
• Iterating through a string Using for Loop
h_letters = []
for letter in 'human':
h_letters.append(letter)
print(h_letters)
• When we run the program, the output will be:
['h', 'u', 'm', 'a', 'n']

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Example 2:
• Iterating through a string Using List Comprehension
h_letters = [ letter for letter in 'human' ]
print( h_letters)
When we run the program, the output will be:
• ['h', 'u', 'm', 'a', 'n']

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


>>> sentence = 'the rocket came back from mars'
>>> vowels = [i for i in sentence if i in 'aeiou']
>>> vowels
['e', 'o', 'e', 'a', 'e', 'a', 'o', 'a']

https://realpython.com/list-comprehension-python/

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Example 3: Nested IF with List Comprehension
num_list = [y for y in range(100) if y % 2 == 0 if y % 5 ==
0] print(num_list)

• When we run the above program, the output will be:


• [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Example 4: if...else With List Comprehension
>>> obj = ["Even" if i%2==0 else "Odd" for i in range(10)]
>>> print(obj)
When we run the above program, the output will be:
['Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even',
'Odd']

https://www.programiz.com/python-programming/list-comprehension
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Python String split()
• The split() method breaks up a string at the specified separator and returns a list of
strings.
• The syntax of split() is:
str.split([separator [, maxsplit]])
• split() Parameters
• split() method takes a maximum of 2 parameters:
• separator (optional)- It is a delimiter. The string splits at the specified separator.
If the separator is not specified, any whitespace (space, newline etc.) string is a
separator.
• maxsplit (optional) - The maxsplit defines the maximum number of splits.
The default value of maxsplit is -1, meaning, no limit on the number of splits.
• Return Value from split()
• split() breaks the string at the separator and returns a list of strings.
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Example 1: How split() works in Python?
>>> text= 'Love thy neighbor'
>>> print(text.split()) # splits at space
>>> grocery = 'Milk, Chicken, Bread'
>>> print(grocery.split(', ')) # splits at ','
>>> print(grocery.split(':')) # Splitting at ':'

• Output
• ['Love', 'thy', 'neighbor']
• ['Milk', 'Chicken', 'Bread']
• ['Milk, Chicken, Bread']
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Example 2: How split() works when maxsplit is specified?
>>> grocery = 'Milk, Chicken, Bread, Butter'
>>> print(grocery.split(', ', 2)) # maxsplit: 2
>>> print(grocery.split(', ', 1)) # maxsplit: 1
>>> print(grocery.split(', ', 5)) # maxsplit: 5
>>> print(grocery.split(', ', 0)) # maxsplit: 0
Output
• ['Milk', 'Chicken', 'Bread, Butter']
• ['Milk', 'Chicken, Bread, Butter']
• ['Milk', 'Chicken', 'Bread', 'Butter']
• maxsplit
If ['Milk, Chicken, Bread,
is specified, the listButter']
will have the maximum of maxsplit+1 items.
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Python map()
• The map() function applies a given function to each item of an iterable (list, tuple etc.) and
returns a list of the results.
• The syntax of map() is:
map(function, iterable, ...)
• map() Parameter
• function - map() passes each item of the iterable to this function.
• iterable - iterable which is to be mapped
• You can pass more than one iterable to the map() function.
• Return Value from map()
• The map() function applies a given to function to each item of an iterable and returns a list of
the results.
• The returned value from map() (map object) can then be passed to functions like list() (to create
a list), set() (to create a set) and so on.
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
>>> a, b = input().split()
12
>>> a
'1'
>>> b
'2'
>>> a, b, c = input().split()
123
>>> a
'1'
>>> b
'2'
>>> c
'3'
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
map() function

>>> a, b, c = map(int,input().split())
123
>>> a
1
>>> b
2
>>> c
3

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


list function

>>> l = list(map(int, input().split()))


1 2 3 4 5 6 7 8 9 10
>>> l
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Python String Module
• Python String module contains some constants, utility function, and classes for string
manipulation.
• It’s a built-in module and we have to import it before using any of its constants and classes.
• String Module Constants
• Let’s look at the constants defined in the string module.
>>> import string # string module constants
>>> print(string.ascii_letters)
>>> print(string.ascii_lowercase)
>>> print(string.ascii_uppercase)
>>> print(string.digits)
>>> print(string.hexdigits)
>>> print(string.whitespace) # ' \t\n\r\x0b\x0c'
>>> print(string.punctuation)
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Output:
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWX
YZ
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
0123456789abcdefABCDEF

!"#$%&'()*+,-./:;?@[\]^_`{|}~
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
Python String splitlines() Method

• The splitlines() method splits a string into a list. The splitting


is done at line breaks.
• Example
• Split a string into a list where each line is a list item:
>>> txt = ”Thank you for the music\nWelcome to the jungle”
>>> x = txt.splitlines()
>>> print(x)

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Comprehensions in Python
• Comprehensions in Python are syntactic constructs that are used to
build sequences from other sequences.
• Essentially, comprehensions are a fancy form of writing for loops
that are more concise and readable.
• All comprehensions can be rewritten using for loops but the vice-
versa doesn’t hold true. At large, there are four types of
comprehension techniques in Python.
• List Comprehensions
• Dictionary Comprehensions
• Set Comprehensions
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
• Generator Comprehensions
Set and Dictionary Comprehensions
• One type of syntactic sugar that sets Python apart from more
verbose languages is comprehensions.
• Comprehensions are a special notation for building up
lists, dictionaries and sets from other lists, dictionaries and sets,
modifying and filtering them in the process.
• Python 3 also introduced set comprehensions. Prior to this, you
could use the set built-in function.
• The syntax for set comprehensions is almost identical to that of
list comprehensions, but it uses curly brackets instead of square
brackets.
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
{} set comprehension
• Description
• Returns a set based on existing iterables.
• Syntax
• {expression(variable) for variable in input_set [predicate][, …]}
• Expression Optional. An output expression producing members of the new set from
members of the input set that satisfy the predicate expression.
• variable Required. Variable representing members of an input set.
• input_set Required. Represents the input set.
• predicate Optional. Expression acting as a filter on members of the input
• set.[, …]] Optional. Another nested comprehension.
• Return Value
• set
Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024
• Example
>>> {s**2 for s in range(10)}
{0, 1, 64, 4, 36, 9, 16, 49, 81, 25}
>>> {s for s in [1, 2, 3] if s % 2}
{1, 3}

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Dictionary Comprehensions
• Syntax of Dictionary Comprehensions
• Consider the following code that creates a dictionary from a range
of numbers with the value being the square of the key:
• square_dict = {num: num*num for num in range(1, 6)}
print(square_dict)
#Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


>>> fruits = ['Apple', 'Orange', 'Papaya', 'Banana', '']
>>> fruits_dict = {f:len(f) for f in fruits if len(f) > 0}
>>> print(fruits_dict)
#Output
{'Apple': 5, 'Orange': 6, 'Papaya': 6, 'Banana': 6}

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


Invert the Mapping of a Dictionary
• In cases, where your dictionary has unique keys and values and
would like to invert the mapping from k:v to v:k you could do it
dictionary comprehension:
>>> d = {'1': 'a', '2': 'b', '3': 'c', '4': 'd'}
>>> my_dict = {v: k for k, v in d.items()}
#Output
{'a': '1', 'b': '2', 'c': '3', 'd': '4'}

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


• # dictionary comprehension example
>>> square_dict = {num: num*num for num in range(1, 11)}
>>> print(square_dict)

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024


>>> keys = ['a','b','c','d','e']
>>> values = [1,2,3,4,5]
• #this line shows dict comprehension here
>>> myDict = { k:v for (k,v) in zip(keys, values)}
• # We can use below too
• # myDict = dict(zip(keys, values))
>>> print (myDict)
• Output :
>>> {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
https://towardsdatascience.com/7-handy-use-cases-of-dictionary-comprehensions-in-python-f7c37e462d92

Python Programming Nssv Prasad Kavitapu Sunday, November 24, 2024

You might also like