0% found this document useful (0 votes)
30 views230 pages

5 Python Collections

The document discusses different types of collections in Python including lists, tuples, sets, and dictionaries. It provides details on lists, including how to create, access, modify, loop through and perform common operations on lists.

Uploaded by

mandalgaurav350
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
30 views230 pages

5 Python Collections

The document discusses different types of collections in Python including lists, tuples, sets, and dictionaries. It provides details on lists, including how to create, access, modify, loop through and perform common operations on lists.

Uploaded by

mandalgaurav350
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 230

Python

Collections
Introduction

 There are four collection data types in the Python programming language:
 List is a collection which is ordered and changeable. Allows duplicate members.
 Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
 Set is a collection which is unordered and unindexed. No duplicate members.
 Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.
 When choosing a collection type, it is useful to understand the properties of that type. Choosing the
right type for a particular data set could mean retention of meaning, and, it could mean an increase in
efficiency or security.
LIST
List
A list is a collection which is ordered and changeable. In Python lists are written with square brackets.
It can have any number of items and they may be of different types (integer, float, string
etc.).
How to create a list?

# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
# list with mixed datatypes
my_list = [1, "Hello", 3.4]
Also, a list can even have another list as an item. This is called nested list.
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
How to access elements from a list?

 Index: a number specifying the position of an element in a listIndex of first element in the list is 0,
second element is 1, and n’th element is n-1
 Negative indexes identify positions relative to the end of the list
 We can use the index operator [] to access an item in a list. Index starts from 0. So, a list having 5
elements will have index from 0 to 4.
 Trying to access an element other that this will raise an IndexError. The index must be an integer.
We can't use float or other types, this will result into TypeError.
 Nested list are accessed using nested indexing.
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.
 my_list = ['p','r','o','b','e']
 print(my_list[-1])
# Output: e
 print(my_list[-5])
# Output: p
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

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

insert() S
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
Operators Description Example

+ Concatenation List1+List2

* Repetition List2*2

[] Slice List2[2]

[:] Range slice List2[1,3]

In Membership
Slicing
 Slice: a span of items that are taken from a sequence
 List slicing format: list[start : end]
 Span is a list containing copies of elements from start up to, but not including,
end
 If start not specified, 0 is used for start index
 If end not specified, len(list) is used for end index
 Slicing expressions can include a step value and negative indexes relative to end
of list
 We can access a range of items in a list by using the slicing operator (colon).
Examples:
 my_list = ['p','r','o','g','r','a','m','i','z']
 print(my_list[2:5]) # elements 3rd to 5th
 print(my_list[:-5]) # elements beginning to 4th
 print(my_list[5:]) # elements 6th to end
 print(my_list[:])# elements beginning to end
 Slicing can be best visualized by considering the index to be between the elements as
shown below. So if we want to access a range, we need two index that will slice that
portion from the list.
Loop Through a List

 You can loop through the list items by using a for loop:
 Print all items in the list, one by one:
 mylist = ["apple", "banana", "cherry"]
for x in mylist:
print(x)
Check if Item Exists- in and not in
operator(Membership operator)
 You can use the in operator to determine whether an item is contained in a list
 General format: item in list
 Returns True if the item is in the list, or False if it is not in the list
 Similarly you can use the not in operator to determine whether an item is not in a
list
 Check if "apple" is present in the list:
 mylist = ["apple", "banana", "cherry"]
if "apple" in mylist:
print("Yes, 'apple' is in the fruits list")
List Length
To determine how many items a list has, use
the len() method:
Print the number of items in the list:
mylist = ["apple", "banana", "cherry"]
print(len(mylist))
Add Items to list
 To add an item to the end of the list, use the append() method:
 Using the append() method to append an item:
 mylist = ["apple", "banana", "cherry"]
mylist.append("orange")
print(mylist)
 To add an item at the specified index, use the insert() method:
 Insert an item as the second position:
 mylist = ["apple", "banana", "cherry"]
mylist.insert(1, "orange")
print(mylist)
Remove Item from list
 There are several methods to remove items from a list:
 The remove() method removes the specified item.
 mylist = ["apple", "banana", "cherry"]
mylist.remove("banana")
print(mylist)
 The pop() method removes the specified index, (or the last item if index is not
specified):
 mylist = ["apple", "banana", "cherry"]
mylist.pop()
print(mylist)
del keyword
 The del keyword removes the specified index
 mylist = ["apple", "banana", "cherry"]
del mylist[0]
The del keyword can also delete the list completely
 mylist = ["apple", "banana", "cherry"]
del mylist
#this will cause an error because "mylist" no longer exists.
 The clear() method empties the list:
 mylist = ["apple", "banana", "cherry"]
mylist.clear()
print(mylist)
Concatenating List

 Concatenate: join two things together


 The + operator can be used to concatenate two lists
 Cannot concatenate a list with another data type, such as a number
 The += augmented assignment operator can also be used to
concatenate lists
Repetition of List

 The * operator can be used to concatenate two


lists
The list() Constructor

Itis also possible to use the list() constructor to


make a list.
mylist = list(("apple", "banana", "cherry"))
# note the double round-brackets
print(mylist)
extend() method:
 The extend() extends the list by adding all items of a list (passed as an argument) to the end.
language = ['French', 'English', 'German']
language1 = ['Spanish', 'Portuguese']
language.extend(language1)
print('Language List: ', language)
index():
In simple terms, index() method finds the given element in a list and returns its position.
vowels = ['a', 'e', 'i', 'o', 'i', 'u']
index = vowels.index('e')
print('The index of e:', index)
count():

 count()method counts how many times an element has occurred in a list


and returns it.
# 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)
reverse():
 The reverse() method reverses the elements of a given list.
 os = ['Windows', 'macOS', 'Linux']
 print('Original List:', os)
 os.reverse()
 print('Updated List:', os)
sort() method:
 The sort() method sorts the elements of a given list.in a specific order - Ascending or Descending.
 list.sort(key=..., reverse=...)
 sorted(list, key=..., reverse=...)

 Note: Simplest difference between sort() and sorted() is: sort() doesn't return any value while, sorted() returns an iterable
list.
 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(): sort() method doesn't return any value. Rather, it changes the original list.
 If you want the original list, use sorted().
 vowels = ['e', 'a', 'u', 'o', 'i']
 vowels.sort()
 print('Sorted list:', vowels)
Sort() example:
OR Sort the list in descending order
vowels.sort(reverse=True)
print('Sorted list (in Descending):', vowels)

OR : Sort using key


def takeSecond(elem):
return elem[1]
random = [(2, 2), (3, 4), (4, 1), (1, 3)]
random.sort(key=takeSecond)
print('Sorted list:', random)
Copying a List

 To make a copy of a list you must copy each element of the list

 Two methods to do this:


 Creating a new empty list and using a for loop to add a copy of each element from the original list to
the new list
 Creating a new empty list and concatenating the old list to the new empty list
 l1=[34,56,67,67,673,637]
 l2=l1 #shallow copy

 l3=l1.copy() # deep copy

 l4=l1[:] #deep copy

 print(id(l1))
 print(id(l2))
 print(id(l3))
 print(id(l4))
Cloning a List
 You can use the slice operator with a default START and END to clone
an entire list (make a copy of it)
 For example:
a = [ 5, 10, 50, 100]
b = a[: ]
Now, a and b point to different copies of the list with the same data
values.
Zipping List together

>>> names=['ben', 'chen', 'yaqin']


>>> password=[“aaaa”,”bbbb”,’”cccc”]
>>> list(zip(names,password)
Output: list of tuples
Nested List

 n_list = ["Happy", [2,0,1,5]]


# Nested indexing
 print(n_list[0][1])
# Output: a
 print(n_list[1][3])
# Output: 5
2-D List
2-D List

 Two-dimensional list: a list that contains other lists as its elements


 Also known as nested list
 Common to think of two-dimensional lists as having rows and columns
 Useful for working with multiple sets of data
 To process data in a two-dimensional list need to use two indexes
 Typically use nested loops to process
 The last element added is the first element retrieved
List Comprehension: Elegant way to
create new List
List comprehension is an elegant and concise way to create new list from an existing list
in Python.
List comprehension consists of an expression followed by for statement inside square
brackets.
Here is an example to make a list with each item being increasing power of 2.
pow2 = [2 ** x for x in range(10)]
0 to 10 , 2 raised to 0 to 2 raised 9
# Output: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
print(pow2)
This code is equivalent to
pow2 = []
for x in range(10):
pow2.append(2 ** x)
Some more example

These aren't really functions, but they can replace functions (or maps, filters, etc)
A list comprehension can optionally contain more for or if statements. An
optional ifstatement can filter out items for the new list. Here are some examples.
>>> pow2 = [2 ** x for x in range(10) if x > 5]
>>> pow2
[64, 128, 256, 512]
>>> odd = [x for x in range(20) if x % 2 == 1]
>>> odd
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> [x+y for x in ['Python ','C '] for y in ['Language','Programming']]
['Python Language', 'Python Programming', 'C Language', 'C Programming']
Some more examples:

a= [x**2 for x in range(9)]


[0, 1, 4, 9, 16, 25, 36, 49, 64]
b= [x**2 for x in range(10) if x%2 == 0]
[0, 4, 16, 36, 64]
c=[x+y for x in [1,2,3] for y in [100,200,300]]
[101, 201, 301, 102, 202, 302, 103, 203, 303]
Some more functions

len() Return the length (the number of items) in the list.


list() Convert an iterable (tuple, string, set, dictionary) to a list.
max() Return the largest item in the list.
min() Return the smallest item in the list
sorted() Return a new sorted list (does not sort the list itself).
sum() Return the sum of all elements in the list.
Using Lists as Stacks
 To add an item to the stack,
 append() must be used
 stack = [3, 4, 5]
 stack.append(6)
 Stack is now [3, 4, 5, 6]
 To retrieve an item from the top of the stack, pop must be used
 Stack.pop()
 6 is output
 Stack is now [3, 4, 5] again
Using Lists as Queues

First element added is the first element retrieved


To do this collections.deque
must be implemented
TUPLE
Tuple
A tuple is a collection which is
ordered and unchangeable. In
Python tuples are written with
round brackets.
Create a Tuple:
#empty tuple
mytuple=(,)
#tuple with values
mytuple = ("apple", "banana", "cherry")
print(mytuple)
Access Tuple Items
 Youcan access tuple items by referring to the index number, inside
square brackets:
 Return the item in position 1:
mytuple = ("apple", "banana", "cherry")
print(mytuple[1])
 Using loop:
for var in tuple1:
print(var)
Change Tuple Values
 Oncea tuple is created, you cannot change its values.
Tuples are unchangeable.
 You cannot change values in a tuple:
mytuple = ("apple", "banana", "cherry")
mytuple[1] = "blackcurrant"
# The values will remain the same:
print(mytuple)
Loop Through a Tuple
You can loop through the tuple items by using a for
loop.
Iterate through the items and print the values:

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


for x in mytuple:
print(x)
Check if Item Exists: in and not in operator(Membership
operator)

 Todetermine if a specified item is present in a tuple use the in


keyword:
 Check if "apple" is present in the tuple:
mytuple = ("apple", "banana", "cherry")
if "apple" in mytuple:
print("Yes, 'apple' is in the fruits tuple")
Tuple Length
To determine how many items a tuple has, use the
len() method:
Print the number of items in the tuple:

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


print(len(mytuple))
Add Items
Once a tuple is created, you cannot add items to it.
Tuples are unchangeable.
You cannot add items to a tuple:

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


mytuple[3] = "orange" # This will raise an error
print(mytuple)
Remove Items
 Tuplesare unchangeable, so you cannot remove items from it,
but you can delete the tuple completely:
 The del keyword can delete the tuple completely:
mytuple = ("apple", "banana", "cherry")
del mytuple
print(mytuple)
#this will raise an error because the tuple no longer exists
The tuple() Constructor
 Itis also possible to use the tuple() constructor to make a
tuple.
 Using the tuple() method to make a tuple:
mytuple = tuple(("apple", "banana", "cherry"))
# note the double round-brackets
print(mytuple)
TUPLE OPERATOR

Operators Description Example


+ Concatenation Tuple1+tuple2
* Repetition tuple2*2
[] Slice tuple2[2]
[:] Range slice tuple21,3]
In Membership
TUPLE METHODS

Method Description
count() Returns the number of times a specified value occurs in a tuple

index() Searches the tuple for a specified value and returns the position
of where it was found
SET
Set

A set is a collection which is


unordered and unindexed. In
Python sets are written with
curly brackets.
Create a Set:
 A setcan consist of a mixture of different types of
elements
 my_set = {'a',1,3.14159,True}
 myset = {"apple", "banana", "cherry"}
print(myset)
 Note:Sets are unordered, so the items will appear in a
random order.
Access Items
 You cannot access items in a set by referring to an index, since sets are unordered the items has no
index.
 But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by
using the in keyword.
 Loop through the set, and print the values:
 myset = {"apple", "banana", "cherry"}
 for x in myset:
 print(x)
 Check if "banana" is present in the set:
 myset = {"apple", "banana", "cherry"}
 print("banana" in myset)
Change Items and Add Items
 Once a set is created, you cannot change its items, but you can add new items
 To add one item to a set: use the add() method.
 To add more than one item to a set use the update() method.
Add an item to a set, using the add() method:
 myset = {"apple", "banana", "cherry"}
 myset.add("orange")
 print(myset)
Add multiple items to a set, using the update() method:
 myset = {"apple", "banana", "cherry"}
 myset.update(["orange", "mango", "grapes"])
 print(myset)
Get the Length of a Set
To determine how many items a set has, use
the len() method.
Get the number of items in a set:
myset = {"apple", "banana", "cherry"}
print(len(myset))
Remove Item
 To remove an item in a set, use the remove(), or the discard() method.
 Remove "banana" by using the remove() method:
 myset = {"apple", "banana", "cherry"}
 myset.remove("banana")
 print(myset)
 Note: If the item to remove does not exist, remove() will raise an error.
 Remove "banana" by using the discard() method:
 myset = {"apple", "banana", "cherry"}
 myset.discard("banana")
 print(myset)
pop() method
 Note: If the item to remove does not exist, discard() will NOT raise an error.
 You can also use the pop(), method to remove an item, but this method will remove the last item.
Remember that sets are unordered, so you will not know what item that gets removed.
 The return value of the pop() method is the removed item.
 Remove the last item by using the pop() method:
 myset = {"apple", "banana", "cherry"}
 x = myset.pop()
 print(x)
 print(myset)
 Note: Sets are unordered, so when using the pop() method, you will not know which item that gets
removed.
Clear() & del keyword
 The clear() method empties the set:
 myset = {"apple", "banana", "cherry"}
 myset.clear()
 print(myset)
 The del keyword will delete the set completely:
 myset = {"apple", "banana", "cherry"}
 del myset
 print(myset)
The set() Constructor

Itis also possible to use the set() constructor to


make a set.
Using the set() constructor to make a set:
myset = set(("apple", "banana", "cherry")) # note
the double round-brackets
print(myset)
Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference between two
or more sets
difference_update() Removes the items in this set that are also included
in another, specified set
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two other
sets
intersection_update() Removes the items in this set that are not present in
other, specified set(s)
isdisjoint() Returns whether two sets have a intersection or not:
true if no common ,false is common elements
issubset() Returns whether another set contains this set or not
Method Description
pop() Removes an element from the set
remove() Removes the specified element

symmetric_difference() Returns a set with the symmetric differences of two sets

symmetric_difference_up inserts the symmetric differences from this set and


date() another

union() Return a set containing the union of sets


update() Update the set with the union of this set and others
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().
 A = {1, 2, 3, 4, 5}
 B = {4, 5, 6, 7, 8}
 print(A | B)
 OR:
 # use union function
 A.union(B)
 {1, 2, 3, 4, 5, 6, 7, 8}
 B.union(A)
 {1, 2, 3, 4, 5, 6, 7, 8}
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}
# Output: {4, 5}
print(A & B)
OR
>>> A.intersection(B)
{4, 5}
# use intersection function on B
>>> B.intersection(A)
{4, 5}
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.
 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.
 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
 Cremains unchanged
Example 1: How intersection_update()
Works?
 A = {1, 2, 3, 4}
 B = {2, 3, 4, 5}
 result = A.intersection_update(B)
 print('result =', result)
 print('A =', A)
 print('B =', B)
 When you run the program, the output will be: result = None
 A = {2, 3, 4}
 B = {2, 3, 4, 5, 6}
Example 2: intersection_update() with
Two Parameters
 A = {1, 2, 3, 4} B = {2, 3, 4, 5, 6} C = {4, 5, 6, 9, 10}
 result = C.intersection_update(B, A)
 print('result =', result)
 print('C =', C)
 print('B =', B)
 print('A =', A)
 When you run the program, the output will be: result = None
 C = {4}
 B = {2, 3, 4, 5, 6}
 A = {1, 2, 3, 4}
Set Difference
 Difference of A and B (A - B) is a set of elements that are only in A but not in B. Similarly, B - A is
a set of element in B but not in A.
 Difference is performed using - operator. Same can be accomplished using the method
difference().
 A = {1, 2, 3, 4, 5}
 B = {4, 5, 6, 7, 8}
 # Output: {1, 2, 3}
 print(A - B)
 OR
 A.difference(B)
 {1, 2, 3}
Set difference_update()
 The difference_update() updates the set calling difference_update() method with the difference of sets.
 If A and B are two sets. The set difference of A and B is a set of elements that exists only in set A but not in B.
 To learn more, visit Python set difference.
 The syntax of difference_update() is: A.difference_update(B)
 Here, A and B are two sets. The difference_update() updates set A with the set difference of A-B.
 Return Value from difference_update()
 The difference_update() returns None indicating the object (set) is mutated.
 result = A.difference_update(B)
 When you run the code, result will be None
 A will be equal to A-B
 B will be unchanged
Example: How difference_update() works?

 A = {'a', 'c', 'g', 'd'}


 B = {'c', 'f', 'g'}
 result = A.difference_update(B)
 print('A = ', A)
 print('B = ', B)
 print('result = ', result)
 When you run the program, the output will be:
 A = {'d', 'a'}
 B = {'c', 'g', 'f'}
 result = None
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().
 A = {1, 2, 3, 4, 5}
 B = {4, 5, 6, 7, 8}
 # use ^ operator
 # Output: {1, 2, 3, 6, 7, 8}
 print(A ^ B)
 # use symmetric_difference function on A
 >>> A.symmetric_difference(B)
 {1, 2, 3, 6, 7, 8}
Set symmetric_difference_update()
 The symmetric_difference_update() method updates the set calling the
symmetric_difference_update() with the symmetric difference of sets.
 The symmetric difference of two sets is the set of elements that are in either of the sets but not in
both.
 The syntax of symmetric_difference_update() is:
 A.symmetric_difference_update(B)
 Symmetric_difference_update() Parameters
 The symmetric_difference_update() takes a single argument (set).
 Return Value from symmetric_difference_update()
 This method returns None (meaning, absence of a return value). It only updates the set calling
symmetric_difference_update() method (set A) with the symmetric difference of sets (A and B).
Example: How symmetric_difference_update()
works?
 A = {'a', 'c', 'd'}
 B = {'c', 'd', 'e' }
 result = A.symmetric_difference_update(B)
 print('A = ', A)
 print('B = ', B)
 print('result = ', result)
 When you run the program, the output will be:
 A = {'a', 'e'}
 B = {'d', 'c', 'e'}
 result = None
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.
 The syntax of isdisjoint() is:
 set_a.isdisjoint(set_b)
 The isdisjoint() method takes a single argument (a set).
 You can also pass an iterable (list, tuple, dictionary and string) to disjoint(). The isdisjoint() method will automatically
convert iterables to set and checks whether the sets are disjoint or not.
 The isdisjoint() method returns: True if two sets are disjoint sets (if set_a and set_b are disjoint sets in above syntax)
False if two sets are not disjoint sets
A = {1, 2, 3, 4} B = {5, 6, 7} C = {4, 5, 6}
print('Are A and B disjoint?', A.isdisjoint(B))
print('Are A and C disjoint?', A.isdisjoint(C))
Are A and B disjoint? True
Are A and C disjoint? False
issubset()
 The issubset() method returns True if all elements of a set are present in another set (passed as an
argument). If not, it returns False.
 Set A is said to be the subset of set B if all elements of A are in B .
 Here, set A is a subset of B.
 A.issubset(B)
 The above code checks if A is a subset of B.
 The issubset() returns
 True if A is a subset of B
 False if A is not a subset of B
Example: How issubset() works?

 A = {1, 2, 3}
 B = {1, 2, 3, 4, 5}
 C = {1, 2, 4, 5}
 print(A.issubset(B))
 print(B.issubset(A))
 print(A.issubset(C))
 print(C.issubset(B))
issuperset()
 The issuperset() method returns True if a set has every elements of another set (passed as an
argument). If not, it returns False.
 Set A is said to be the superset of set B if all elements of B are in A.
 here, set A is a superset of set B and B is a subset of set A.
 The syntax of issuperset() is:
 A.issuperset(B)
 Return Value from issuperset()
 The issuperset() returns
 • True if A is a superset of B
 • False if A is not a superset of B
Example:

 A = {1, 2, 3, 4, 5}
 B = {1, 2, 3}
 C = {1, 2, 3}
 print(A.issuperset(B))
 print(B.issuperset(A))
 print(C.issuperset(B))
 True
 False
 True
Frozen Set
 These sets cannot be redefined once they are declared as
frozen set. Hence, they are called as immutable set.
 Set2=frozenset({‘a’,’b’,’c’,’d’})
 This datatype supports methods like copy(), difference(),
intersection(), isdisjoint(), issubset(), issuperset(),
symmetric_difference() and union(). Being immutable it does
not have method that add or remove elements.
STRING
String
 A string is a sequence of characters. The string is a sequence of Unicode character in Python. Unicode was
introduced to include every character in all languages and bring uniformity in encoding.
 Strings can be created by enclosing characters inside a single quote or double quotes. Even triple quotes can be
used in Python but generally used to represent multiline strings and docstrings.
 my_string = 'Hello'
 my_string = "Hello"
 my_string = '''Hello'''
 # triple quotes string can extend multiple lines
 my_string = """Hello, welcome to the
 world of Python"""
Accessing String
 We can access individual characters using indexing and a range of characters using slicing. Trying to access a character out of index range will
raise an IndexError. The index must be an integer. We can't use float or other types, this will result into TypeError. Python allows negative
indexing for its sequences.
 str = 'programing'
 print('str = ', str)
 #first character
 print('str[0] = ', str[0])
 #last character
 print('str[-1] = ', str[-1])
 #slicing 2nd to 5th character
 print('str[1:5] = ', str[1:5])
 #slicing 6th to 2nd last character
 print('str[5:-2] = ', str[5:-2])
Update string:
 The existing string can be update 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' )
 output: Updated String :- Hello Python
String functions
4 string functions.docx
Backslash notation Hexadecimal character Description

\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
Operator Description Example

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

* Repetition - Creates new strings, concatenating multiple copies of the a*2 will give -HelloHello
same string

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

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

In Membership - Returns true if a character exists in the given string H in a will give 1

not in Membership - Returns true if a character does not exist in the given M not in a will give 1
string
r/R Raw String - Suppresses actual meaning of Escape characters. The print r'\n' prints \n and print R'\n'prints \n
syntax for raw strings is exactly the 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


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


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
Unicode String
 Normal strings in Python are stored internally as 8-bit ASCII, while Unicode
strings are stored as 16-bit Unicode. This allows for a more varied set of
characters, including special characters from most languages in the world. I'll
restrict my treatment of Unicode strings to the following −
 print u'Hello, world!'
 When the above code is executed, it produces the following result −
 Hello, world!
 As you can see, Unicode strings use the prefix u, just as raw strings use the prefix r.
Ord() and chr() functions:
 In python ord() function used to get integer representation for string character, ord() function takes string argument(a single
unicode character) and return its integer value.
 Similarly, to get string representation of any integer argument function chr() is used in python.
 Example 1:
ch=‘A’
print(ord(ch))
print(chr(97))
print(ord(‘A’))
 Example 2:
str=“Hello”
if(‘e’ in str):
print(“ e is present in the string”)

else:
print(“e is not present in the string”)
Concatenation of Two or More Strings

 Joining of two or more strings into a single one is called concatenation.


 The + operator does this in Python. Simply writing two string literals together also concatenates
them.
 The * operator can be used to repeat the string for a given number of times.
str1 = 'Hello‘
str2 ='World!‘
# using +
print('str1 + str2 = ', str1 + str2)
# using *
print('str1 * 3 =', str1 * 3)
format() function
 # default(implicit)
 orderdefault_order = "{}, {} and {}".format('John','Bill','Sean')print('\n--- Default Order ---')
 print(default_order)
 # order using positional argument
 positional_order = "{1}, {0} and {2}".format('John','Bill','Sean')print('\n--- Positional Order ---')
 print(positional_order)
 # order using keyword argument
 keyword_order = "{s}, {b} and {j}".format(j='John',b='Bill',s='Sean')print('\n--- Keyword Order
---')print(keyword_order)
lower(), upper(), join(),split(), find(),
replace
 >>> "PrOgRaMiZ".lower() 'programiz'
 >>> "PrOgRaMiZ".upper() 'PROGRAMIZ'
 >>> "This will split all words into a list".split()
 ['This', 'will', 'split', 'all', 'words', 'into', 'a', 'list']
 >>> ' '.join(['This', 'will', 'join', 'all', 'words', 'into', 'a', 'string'])
 'This will join all words into a string'
 >>> 'Happy New Year'.find('ew') 7
 >>> 'Happy New Year'.replace('Happy','Brilliant') 'Brilliant New Year'
 number = "5"
 letters = "abcdef"
 print(number.isnumeric())
 print(letters.isnumeric())
str ="programiz“
#capitalize first letter
print('str.capitalize() = ', str.capitalize())
#computes length of a string
print('len(str) = ', len(str))
Comparing String
 We can use relational operator in string comparison. It uses ASCII value
of each character from start for comparsion.
 Example:
 print(“Hello”)
 print(“Atharva” != “Atharv”)
 print(“Atharva”< “Pikku”)
 print(“right”>=“left”)
Iterating Strings
 Strings are in sequence type and are iterable, we can iterate, strings using
different ways as follows:
 1. using for() loop :
str =“Python”
for i in Str:
print(i)
 2. using Range() function:
for i in range(len(str)):
print(str[i])
Iterating Strings
 Use of [] operator
 We need to provide 3 parameters to slice operator as follows:
 String[start : stop: step] e.g. str[0,9,1]
 for i in str[0:3:1]
 print(i)
 for i in str[ : : 2]
 print(i)
 for i in str[ : :-1] # reverse printing
 print(i)
Python Partition in string
 The Python Partition is one of the Python String Method which is used to split the given string using the specified separator and
return a tuple with three arguments. This Python partition function will start looking for the separator from Left Hand side and
once it finds the separator, it will return the string before the Separator as Tuple Item 1, Separator itself as Tuple Item 2 and
remaining string (or string after the Separator) as Tuple Item 3.
 Syntax of a Partition Function in Python
String_Value.partition(Separator)
String_Value: Please select the valid String variable or you can use the String directly.
Separator: This argument is required and if you forget this argument, python will throw TypeError.
 NOTE: If you pass the non existing item as the separator then Python partition function will return the whole string as Tuple
Item 1 followed by two empty tuple items.
 Return Value: Python Partition function will return Tuple with three arguments. For example, If we have A*B*C and If we use *
as separator. The Python Partition function will search for * from left to right. Once it find * it will return the string before the *
symbol as Tuple Item 1 (A), * as Tuple Item 2 and remaining string as Tuple Item 3 (B*C)
 TIP: Even though there are multiple occurrences of the separator, Partition function will look for the first occurrence
Python Partition method Example
 Str1 = 'Tutorial Gateway'
 Str2 = 'Learn-Python-Programming'
 Str3 = 'xyz@yahoo.com'
 Str4 = Str1.partition(' ')
 print("After Partitioning String 1 = ", Str4)
 Str5 = Str2.partition('-')
 print("After Partitioning String 2 = ", Str5)
 Str6 = Str3.partition('@')
 print("After Partitioning String 3 = ", Str6)
 #Performing Python Partition function directly
 Str7 = 'First_Image.png'.partition('.')
 print("After Partitioning String 7 = ", Str7)
String module : use import
string
Function output
string.ascii_letters 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

string.ascii_lowercase 'abcdefghijklmnopqrstuvwxyz'
string.ascii_uppercase 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.digits '0123456789'
string.hexdigits '0123456789abcdefABCDEF'
string.octdigits '01234567'
string.printable '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUV
WXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'

string.punctuation '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
DICTIONARY
Dictionary
Create and print a dictionary:
 Empty dictionary can be created as shown
dict1={}
Print(dict1)
Print(type(dict1))
 Dictionary with elements
dict2={‘name’:’akshay’,’age’:21,’marks’:88}
print(dict2)
dict1 = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(dict1)
Building Dictionary faster using zip()

 zip creates pairs from two parallel lists


 zip("abc",[1,2,3]) yields
 [('a',1),('b',2),('c',3)]
 That's good for building dictionaries. We call the dict function which takes a list of pairs
to make a dictionary
 dict(zip("abc",[1,2,3])) yields
 {'a': 1, 'c': 3, 'b': 2}
Accessing Items
 You can access the items of a dictionary by referring to its key name, inside square brackets:
 Get the value of the "model" key: x = dict1["model"]
 There is also a method called get() that will give you the same result:
 Get the value of the "model" key:
x = dict1.get("model")

for key in my_dict:

print(key)

 prints all the keys


for key,value in my_dict.items():

print (key,value)

 prints all the key/value pairs


for value in my_dict.values():

print (value)
Adding Elements to dictionary
 Adding an item to the dictionary is done by using a new index key and assigning a value to it:
 EXAMPLE:
dict2={‘name’:’akshay’,’age’:21,’marks’:88}
print(dict2)
dict2[‘city’]=‘London’
print(dict2)
 EXAMPLE:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Remove or delete items:
 Three ways-
 The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
Remove or delete items:
 The popitem() method removes the last inserted item (in versions before 3.7, a random
item is removed instead):
 thisdict = {
 "brand": "Ford",
 "model": "Mustang",
 "year": 1964
 }
 thisdict.popitem()
 print(thisdict)
Remove or delete items:
 The del keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
Remove or delete items:
 The del keyword can also delete the dictionary completely:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
 print(thisdict) #this will cause an error because "thisdict" no longer
exists.
Remove or delete items:
 The clear() keyword empties the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)
Change Values
 Youcan change the value of a specific item by referring to its key
name:
 Change the "year" to 2018:
 dict1={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
dict1["year"] = 2018
Loop Through a Dictionary
 You can loop through a dictionary by using a for loop.
 When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.
 Print all key names in the dictionary, one by one:
for x in dict1:

print(x)

 Print all values in the dictionary, one by one:


for x in thisdict:

print(dict1[x])

 You can also use the values() function to return values of a dictionary:
for x in thisdict.values():

print(x)

 Loop through both keys and values, by using the items() function:
for x, y in thisdict.items():

print(x, y)
Check if Key Exists
 To determine if a specified key is present in a dictionary use the in keyword:
 Check if "model" is present in the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
Dictionary Length
To determine how many items (key-value pairs) a
dictionary has, use the len() method.
Print the number of items in the dictionary:
print(len(thisdict))
The dict() Constructor
Itis also possible to use the dict() constructor to make
a dictionary:
thisdict = dict(brand="Ford", model="Mustang",
year=1964)
# note that keywords are not string literals
# note the use of equals rather than colon for the
assignment
print(thisdict)
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and values
get() Returns the value of the specified key
items() Returns a list containing the a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with
the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary
NESTED
DICTIONARY
What is Nested Dictionary in
Python?
 InPython, a nested dictionary is a dictionary inside a
dictionary. It's a collection of dictionaries into one single
dictionary.
nested_dict = { 'dictA': {'key_1': 'value_1'},
'dictB': {'key_2': 'value_2'}}
 Here,the nested_dict is a nested dictionary with the dictionary
dictA and dictB. They are two dictionary each having own key
and value.
Create a Nested Dictionary

 We're going to create dictionary of people within a dictionary.


 Example 1: How to create a nested dictionary
people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}
print(people)
 In the above program, people is a nested dictionary. The internal dictionary 1 and 2
is assigned to people. Here, both the dictionary have key name, age , sex with
different values. Now, we print the result of people.
Access elements of a Nested
Dictionary
 To access element of a nested dictionary, we use indexing [] syntax in Python.
 Example : Access the elements using the [] syntax
people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}

print(people[1]['name'])
print(people[1]['age'])
print(people[1]['sex'])
How to change or add elements in a nested
dictionary?
 Example : people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}
people[3] = {}
people[3]['name'] = 'Luna'
people[3]['age'] = '24'
people[3]['sex'] = 'Female'
people[3]['married'] = 'No'
 print(people[3]) When we run above program, it will output: {'name': 'Luna', 'age': '24', 'sex': 'Female', 'married': 'No'}
 In the above program, we create an empty dictionary 3 inside the dictionary people.
 Then, we add the key:value pair i.e people[3]['Name'] = 'Luna' inside the dictionary 3. Similarly, we do this for key age, sex
and married one by one. When we print the people[3], we get key:value pairs of dictionary 3.
Add another dictionary to the nested
dictionary
 Example 4:
people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'},
3: {'name': 'Luna', 'age': '24', 'sex': 'Female', 'married': 'No'}}
people[4] = {'name': 'Peter', 'age': '29', 'sex': 'Male', 'married': 'Yes'}
print(people[4])

 When we run above program, it will output: {'name': 'Peter', 'age': '29', 'sex': 'Male', 'married':
'Yes'}
 In the above program, we assign a dictionary literal to people[4]. The literal have keys name, age
and sex with respective values. Then we print the people[4], to see that the dictionary 4is added in
nested dictionary people.
Delete elements from a Nested
Dictionary
 In Python, we use “ del “ statement to delete elements from nested dictionary.
 Example 5: How to delete elements from a nested dictionary?
people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'},
3: {'name': 'Luna', 'age': '24', 'sex': 'Female', 'married': 'No'},
4: {'name': 'Peter', 'age': '29', 'sex': 'Male', 'married': 'Yes'}}
del people[3]['married']
del people[4]['married']
print(people[3])
print(people[4])
 When we run above program, it will output: {'name': 'Luna', 'age': '24', 'sex': 'Female'}
 {'name': 'Peter', 'age': '29', 'sex': 'Male'}
Delete Dictionary from nested dictionary

 Example 6: How to delete dictionary from a nested dictionary?


people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'},
3: {'name': 'Luna', 'age': '24', 'sex': 'Female'},
4: {'name': 'Peter', 'age': '29', 'sex': 'Male'}}
del people[3], people[4]
 print(people)
Iterating Through a Nested Dictionary

 Using the for loops, we can iterate through each elements in a nested
dictionary.
 Example 7: How to iterate through a Nested dictionary?
people = {1: {'Name': 'John', 'Age': '27', 'Sex': 'Male'},
2: {'Name': 'Marie', 'Age': '22', 'Sex': 'Female'}}
for p_id, p_info in people.items():
print("\nPerson ID:", p_id)
for key in p_info:
print(key + ':', p_info[key])
ARRAY IN PYTHON
Array : How to create

 Anarray is a special variable, which can hold more


than one value at a time.
 import array as arr
a =arr.array('d',[1.1,3.5,4.5])
 print(a)
Type Minimum size in
C Type Python Type
code bytes
'b' signed char Int 1
'B' unsigned char Int 1
'u' Py_UNICODE Unicode character 2
'h' signed short Int 2
'H' unsigned short Int 2
'i' signed int Int 2
'I' unsigned int Int 2
'l' signed long Int 4
'L' unsigned long Int 4
'f' Float Float 4
'd' double Float 8
How to access array elements?

 We use indices to access elements of an array:


import array as arr
a =arr.array('i',[2,4,6,8])
print("First element:", a[0])
print("Second element:", a[1])
print("Second last element:", a[-1])
 Arrays are used to store multiple values in one single variable:
 Remember, index starts from 0 (not 1) similar like lists.
 How to slice arrays?
 We can access a range of items in an array by using the slicing operator :.
import array as arr
numbers_list=[2,5,62,5,42,52,48,5]
numbers_array=arr.array('i',numbers_list)
print(numbers_array[2:5])# 3rd to 5th
print(numbers_array[:-5])# beginning to 4th
print(numbers_array[5:])# 6th to end
print(numbers_array[:])# beginning to end
How to change or add elements?

 Arrays are mutable; their elements can be changed in a similar way like lists.
import array as arr
numbers=arr.array('i',[1,2,3,5,7,10])
# changing first element
numbers[0]=0
print(numbers)# Output: array('i', [0, 2, 3, 5, 7, 10])
# changing 3rd to 5th element
numbers[2:5]=arr.array('i',[4,6,8])
print(numbers)# Output: array('i', [0, 2, 4, 6, 8, 10])
Add items to array

 We can add one item to a list using append() method or add several items
using extend()method.
import array as arr
numbers=arr.array('i',[1,2,3])
numbers.append(4)
print(numbers)# Output: array('i', [1, 2, 3, 4])
# extend() appends iterable to the end of the array
numbers.extend([5,6,7])
print(numbers)# Output: array('i', [1, 2, 3, 4, 5, 6, 7])
concatenate two arrays using + operator.

import array as arr


odd=arr.array('i',[1,3,5])
even=arr.array('i',[2,4,6])
numbers=arr.array('i')# creating empty array of integer
numbers= odd + even
print(numbers)
How to delete elements?

 We can delete one or more items from an array using Python's


del statement.
import array asarr
number=arr.array('i',[1,2,3,3,4])
del number[2]# removing third element
print(number)# Output: array('i', [1, 2, 3, 4])
del number # deleting entire array
print(number)# Error: array is not defined
How to remove elements?

 We can use the remove() method to remove the given


item, and pop() method to remove an item at the given
index.
import array as arr
numbers=arr.array('i',[10,11,12,12,13])
numbers.remove(12)
print(numbers)# Output: array('i', [10, 11, 12, 13])
print(numbers.pop(2))# Output: 12
print(numbers)# Output: array('i', [10, 11, 13])
The Length of an Array

 Use the len() method to return the length of an array (the


number of elements in an array).
 Example
 Return the number of elements in the cars array:
 x = len(cars)
 Note: The length of an array is always one more than the
highest array index.
Looping Array Elements

 You can use the for in loop to loop through all the elements of
an array.
 Example
 Print each item in the cars array:
 for x in cars:
 print(x)
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elem

ents with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position


pop() Removes the element at the specified position

remove() Removes the first item with the specified value

reverse() Reverses the order of the list


sort() Sorts the list
Lists Versus Tuples

 What are common characteristics?


Both store arbitrary data objects
Both are of sequence data type
 What are differences?
Tuple doesn’t allow modification
Tuple doesn’t have methods append,extend, remove ,pop
Tuple supports format strings
Tuple supports variable length parameter in function call.
Tuples slightly faster
Advantages for using tuples over lists:

 Processing tuples is faster than processing lists


 Tuples are safe
 Some operations in Python require use of tuples
Lists Versus Dictionaries

 A liststores an ordered collection of items, so it keeps some order.


Dictionaries don’t have any order.
 Dictionariesare known to associate each key with a value, while lists just
contain values.
 Usea dictionary when you have an unordered set of unique keys that
map to values.
 Note that, because you have keys and values that link to each other, the
performance will be better than lists in cases where you’re checking
membership of an element.
Lists Versus Sets

 Just like dictionaries, sets have no order in their collection of items. Not like lists.
 Set requires the items contained in it to be hashable, lists store non-hashable items.
 Sets require your items to be unique and immutable. Duplicates are not allowed in
sets, while lists allow for duplicates and are mutable.
 You should make use of sets when you have an unordered set of unique, immutable
values that are hashable.
 You aren’t sure which values are hashable?
 Take a look below just to be sure:
Hashable Non-Hashable
Floats Dictionaries
Integers Sets
Tuples Lists
Strings

frozenset()
How To Convert Lists Into Other Data
Structures

 Sometimes, a list is not exactly what you need.


In these cases, you might want to know how to
transform your list to a more appropriate data
structure. Below, we list some of the most
common transformation questions and their
answers.
How To Convert A List To A String
 You convert a list to a string by using ''.join(). This operation allows you to glue together all strings in your list together and return them as a string.
 # List of Strings to a String
 listOfStrings = ['One', 'Two', 'Three']
 strOfStrings = ''.join(listOfStrings)
 print(strOfStrings)
 # List Of Integers to a String
 listOfNumbers = [1, 2, 3]
 strOfNumbers = ''.join(str(n) for n in listOfNumbers)
 print(strOfNumbers)
 str.join(iterable)
 Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects.
The separator between elements is the string providing this method.
 Note that if your list only contains integers, you should convert the elements to strings before performing the join on them. This is illustrated in the second example
in the interactive code block above.
 The conversion from an integer to a string is done by looping over the original listOfNumbers list.
How To Convert A List To A Tuple

 You can change a list to a tuple in Python by using the tuple() function.
Pass your list to this function, and you will get a tuple back!
 Remember: tuples are immutable. You can’t change them afterward!
 Tip: you can try transforming your listOfStrings into a tuple in the
interactive exercise of the next section.
How To Convert Your List To A Set In
Python
 As you will remember, a set is an unordered collection of unique items. That means not only means
that any duplicates that you might have had in your original list will be lost once you convert it to a
set, but also the order of the list elements.
 You can change a list into a set with the set() function. Just pass your list to it!
 Now practice converting your list listOfStrings into a tuple and a set here:
 # Pass your list to `tuple()`
 tuple(___)
 # Transform your list into a set
 set(___)
How To Convert Lists To A Dictionaries

 A dictionary works with keys and values, so the conversion from a list to a dictionary might be less straightforward. Let’s say
you have a list like this:
 helloWorld = ['hello','world','1','2']
 You will need to make sure that ‘hello’ and ‘world’ and ‘1’ and ‘2’ are interpreted as key-value pairs. The way to do this is to
select them with the slice notation and pass them to zip().
 zip() actually works like expected: it zips elements together. In this case, when you zip the helloWorld
elements helloWorld[0::2] and helloWorld[1::2], your output will be:
 list(zip(helloWorld))
 Note that you need to use list() to print out the result of the zip()function.
 You will pass this to the dict() function, which will interpret hello as a key and world as a value. Similarly, 1 will be interpreted
as a key and 2 as a value.
 Run the code below to confirm this:
 # Convert to a dictionary
 helloWorldDictionary = dict(zip(helloWorld[0::2], helloWorld[1::2]))
 # Print out the result
 print(helloWorldDictionary)
 Note that the second element that is passed to the zip() function makes use of the step value to make sure that only
the world and 2 elements are selected. Likewise, the first element uses the step value to select hello and 1.
 If your list is large, you will probably want to do something like this:
 a = [1, 2, 3, 4, 5]
 # Create a list iterator object
 i = iter(a)
 # Zip and create a dictionary
 print(dict(zip(i, i)))
 Note that an iterable object can give you an iterator. The iterator, which has a .__next__ method, holds information on where exactly
you are in your iteration: it knows what the next element in the iteration is.
How To Convert A Tuple To A List

You can change a tuple to a list in Python


by using the list() function. Pass your
tuple to this function, and you will get a
list back!
 We can even convert one sequence to another.
 >>> set([1,2,3]) {1, 2, 3}
 >>> tuple({5,6,7}) (5, 6, 7)
 >>> list('hello') ['h', 'e', 'l', 'l', 'o']
 To convert to dictionary, each element must be a pair
 >>> dict([[1,2],[3,4]]) {1: 2, 3: 4}
 >>> dict([(3,26),(4,44)]) {3: 26, 4: 44}
PROBLEM AND
SOLUTION
#sort list according to length
of element
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=input("Enter element:")
a.append(b)
a.sort(key=len) #sorting
print(a)
# Second largest element in list
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b) #adding element in list
a.sort() #sorting list
print("Second largest element is:",a[n-2]) #accessing element in list
#Python Program to remove the
duplicate items from a list.
l1=[45,89,23,787,343,343,343]
print(l1)
s1=set(l1)
print(s1)
l2=list(s1)
print(l2)
#program to merge two list and sort
a=[]
c=[]
n1=int(input("Enter number of elements:"))
for i in range(1,n1+1):
b=int(input("Enter element:"))
a.append(b)
n2=int(input("Enter number of elements:"))
for i in range(1,n2+1):
d=int(input("Enter element:"))
c.append(d)
new=a+c
new.sort()
print("Sorted list is:",new)
# Program to read a list of words and
return the length of the longest one
li=[]
no=int(input("how many elements:"))
print("\n Enter string elements :")
for i in range(1,no+1):
ele=input()
li.append(ele)
li.sort(key=len)
print(len(li[no-1]))
#program to put even and odd
elements in list into two different list
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
even=[]
odd=[]
for j in a:
if(j%2==0):
even.append(j)
else:
odd.append(j)
print("The even list",even)
print("The odd list",odd)
FIND THE LARGEST ELEMENT
OF LIST
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
a.sort()
print("Largest element is:",a[n-1])
#program to take two and find union of
it
a=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
element=int(input("Enter element" + str(x+1) + ":"))
a.append(element)
b=[sum(a[0:x+1]) for x in range(0,len(a))]
print("The original list is: ",a)
print("The new list is: ",b)
#Program to create a list of tuples with the
first element as the number and the second
element as the square of the number.
l_range=int(input("Enter the lower range:"))
u_range=int(input("Enter the upper range:"))
a=[(x,x**2) for x in range(l_range,u_range+1)]
print(a)
# Python Program to swap the first and last
value of a list.
a=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
element=int(input("Enter element" + str(x+1) + ":"))
a.append(element)
temp=a[0]
a[0]=a[n-1]
a[n-1]=temp
print("New list is:")
print(a)
Python Program to
Replace all Occurrences
of ‘a’ with $ in a String
string=input("Enter string:")
string=string.replace('a','$')
string=string.replace('A','$')
print("Modified string:")
print(string)
Python Program to Remove the nth
Index Character from a Non-
Empty String
string=input("Enter the sring:")
n=int(input("Enter the index of the character to remove:"))
print("Modified string:")
def remove(string, n):
first = string[:n]
last = string[n+1:]
return first + last
print(remove(string, n))
Python Program to Detect if Two Strings are Anagrams
Problem Solution
1. Take two strings from the user and store them in separate variables.
2. Then use sorted() to sort both the strings into lists.
3. Compare the sorted lists and check if they are equal.
4. Print the final result.
5. Exit.
s1=input("Enter first string:")
s2=input("Enter second string:")
if(sorted(s1)==sorted(s2)):
print("The strings are anagrams.")
else:
print("The strings aren't anagrams.")
Count and print Number of
vowels in a string
string=input("Enter string:")
vowels=0
for i in string:
if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E' or
i=='I' or i=='O' or i=='U'):
vowels=vowels+1
print("Number of vowels are:")
print(vowels)
Replace every space in string using
hyphen(-)
string=input("Enter string:")
string=string.replace(' ','-')
print("Modified string:")
print(string)
Calculate length of string
without library function
string=input("Enter string:")
count=0
for i in string:
count=count+1
print("Length of the string is:")
print(count)
Python Program to Remove the
Characters of Odd Index Values in a
String
def modify(string):
final = ""
for i in range(len(string)):
if i % 2 == 0:
final = final + string[i]
return final
string=input("Enter string:")
print("Modified string is:")
print(modify(string))
No of words and no of character in a string
string=input("Enter string:")
char=0
word=1
for i in string:
char=char+1
if(i==' '):
word=word+1
print("Number of words in the string:")
print(word)
print("Number of characters in the string:")
print(char)
Python Program to Take in Two Strings
and Display the Larger String without
Using Built-in Functions
string1=input("Enter first string:")

string2=input("Enter second string:")

count1=0

count2=0

for i in string1:

count1=count1+1

for j in string2:

count2=count2+1

if(count1<count2):

print("Larger string is:")

print(string2)

elif(count1==count2):

print("Both strings are equal.")

else:

print("Larger string is:")

print(string1)
Python Program to Count Number of
Lowercase Characters in a String
string=input("Enter string:")
count=0
for i in string:
if(i.islower()):
count=count+1
print("The number of lowercase characters is:")
print(count)
DICTIONARY
Python Program to Add a Key-Value
Pair to the Dictionary
 key=int(input("Enter the key (int) to be added:"))
 value=int(input("Enter the value for the key to be added:"))
 d={}
 d.update({key:value})
 print("Updated dictionary is:")
 print(d)
Python Program to Concatenate Two
Dictionaries Into One
 d1={'A':1,'B':2}
 d2={'C':3}
 d1.update(d2)
 print("Concatenated dictionary is:")
 print(d1)
Python Program to Check if a Given
Key Exists in a Dictionary or Not
 d={'A':1,'B':2,'C':3}
 key=input("Enter key to check:")
 if key in d.keys():
 print("Key is present and value of the key is:")
 print(d[key])
 else:
 print("Key isn't present!")
 PythonProgram to Generate a Dictionary that
Contains Numbers (between 1 and n) in the
Form (x,x*x).
n=int(input("Enter a number:"))
d={x:x*x for x in range(1,n+1)}
print(d)
Python Program to Sum All the Items in a
Dictionary
d={'A':100,'B':540,'C':239}
print("Total sum of values in the
dictionary:")
print(sum(d.values()))
Python Program to Multiply All the Items
in a Dictionary
d={'A':10,'B':10,'C':239}
tot=1
for iin d:
 tot=tot*d[i]
print(tot)
Python Program to Remove the Given
Key from a Dictionary
 d = {'a':1,'b':2,'c':3,'d':4}
 print("Initial dictionary")
 print(d)
 key=input("Enter the key to delete(a-d):")
 if key in d:
 del d[key]
 else:
 print("Key not found!")
 exit(0)
 print("Updated dictionary")
 print(d)
Python Program to Form a Dictionary
from an Object of a Class
 class A(object):
 def __init__(self):
 self.A=1
 self.B=2
 obj=A()
 print(obj.__dict__)
Python Program to Map Two Lists
into a Dictionary
 keys=[]
 values=[]
 n=int(input("Enter number of elements for dictionary:"))
 print("For keys:")
 for x in range(0,n):
 element=int(input("Enter element" + str(x+1) + ":"))
 keys.append(element)
 print("For values:")
 for x in range(0,n):
 element=int(input("Enter element" + str(x+1) + ":"))
 values.append(element)
 d=dict(zip(keys,values))
 print("The dictionary is:")
 print(d)
set
Python Program to Count the
Number of Vowels Present in a String
using Sets
s=input("Enter string:")
count = 0
vowels = set("aeiou")
for letter in s:
if letter in vowels:
count += 1
print("Count of the vowels is:")
print(count)
Python Program to Check Common
Letters in Two Input Strings
s1=input("Enter first string:")
s2=input("Enter second string:")
a=list(set(s1)&set(s2))
print("The common letters are:")
for i in a:
print(i)
Python Program that Displays
which Letters are in the First
String but not in the Second
s1=input("Enter first string:")
s2=input("Enter second string:")
a=list(set(s1)-set(s2))
print("The letters are:")
for i in a:
print(i)
Python Program that Displays which
Letters are Present in Both the
Strings
s1=input("Enter first string:")
s2=input("Enter second string:")
a=list(set(s1)|set(s2))
print("The letters are:")
for i in a:
print(i)
Python Program that Displays
which Letters are in the Two
Strings but not in Both
s1=input("Enter first string:")
s2=input("Enter second string:")
a=list(set(s1)^set(s2))
print("The letters are:")
for i in a:
print(i)
ASSIGNMENTS
Assignments
1. Write a program that prints all the numbers from 1 to 100. Your program should have
much fewer than 100 lines of code!
2. Suppose you have a Python program that read in a whole page from a book into an
array PAGE, with each item of the array corresponding to a line. Add code to this
program to create a new array SENTENCES that contains the same text, but now with
each element in SENTENCES being one sentence.
3. Let d be a dictionary whose pairs key:value are country:capital. Write a Python
program that prints the keys and values of d, with the keys sorted in alphabetical order.
Test your program on
d = {“France”:”Paris”,”Belgium”:”Brussels”,”Mexico”:”Mexico
City”,”Argentina”:”Buenos Aires”,”China”:”Beijing”}
4. Write a Python program which accepts the user's first and last name and print them in
reverse order with a space between them.
5. Write a Python program to display the first and last colors from the following list.
color_list = ["Red","Green","White" ,"Black"]
6. Write a Python program to count the number 4 in a given list.
7. Write a Python program to test whether a passed letter is a vowel or not.
8. Write a Python program to check whether a specified value is contained in a group of
values.
9. Write a Python program to concatenate all elements in a list into a string and return it.
10. Write a Python program to print out a set containing all the colors from color_list_1 which are not present in color_list_2.
Test Data :
color_list_1 = set(["White", "Black", "Red"]) color_list_2 = set(["Red", "Green"])
Expected Output : {'Black', 'White'}
11. Write a Python program to count the number occurrence of a specific character in a string.
12. Write a Python program to remove the first item from a specified list.
13. Write a Python program to sum of all counts in a collections?
14. Write a Python program to print the length of the series and the series from the given 3rd term, 3rd last term and the sum of a
series.
15. Write a Python program to replace a string "Python" with "Java" and "Java" with "Python" in a given string.
Input:
English letters (including single byte alphanumeric characters, blanks, symbols) are given on one line. The length of the input
character string is 1000 or less.
Input a text with two words 'Python' and 'Java'
Python is popular than Java
Java is popular than Python

You might also like