Professional Documents
Culture Documents
Python
{ Presenter : Mr. C P Bhamare
Python Lists
• List is created by placing all the 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]
• A list can also have another list as an item. This is called a nested list.
# nested list
my_list = [“Hello", [8, 4, 6], ['a']]
Adding Elements to a List
• We can add one item to a list using the append() method or add several
items using extend() method.
• These methods add the elements at the end of the list.
my_list.extend([11, 16,18])
print(my_list) # output : [1,2,3,4,5,10,11,16,18]
Adding Elements to a List
• We can insert one item at a desired location by using the method insert()
• We can insert multiple items by squeezing it into an empty slice of a list.
my_list[3:3] = [15,16,17]
print(my_list) # output : [1,2,10,15,16,17,3,4,5]
Accessing elements from the List
• 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.
# List indexing
my_list = [1, 2, ’Hello’, 3.4, 5]
print(my_list[0]) # Output: 1
print(my_list[2]) # Output: Hello
print(my_list[4]) # Output: 5
print(my_list[4.0]) # error
Accessing elements from the List
# Nested List
my_list = ["Hello", [2, 0, 1, 5]]
# Nested indexing
print(my_list[0][1]) #ouput : e
print(my_list[1][3]) #ouput : 5
Accessing elements from the List
• Python allows negative indexing for its sequences. The index of -1 refers to
the last item, -2 to the second last item and so on.
print(my_list[-1]) #output : N
print(my_list[-5]) #output : Y
Accessing elements from the List
• We can access a range of items in a list by using the slicing operator :(colon).
• We can delete one or more items from a list using the keyword del. It can
even delete the list entirely.
# Deleting list elements
my_list = [1, ‘H’, 3.4, ‘O’, ‘Welcome’]
del my_list[1]
print(my_list) # output : [1, 3.4, ‘O’,’Welcome’]
del my_list[1:4]
print(my_list) # output : [1]
Removing/Deleting elements from the List
• We can use remove() method to remove the given item or pop() method to
remove an item at the given index.
my_list.remove( ‘H’)
print(my_list) # output : [1, 3.4, ‘O’, ’Welcome’]
my_list.pop(1 )
print(my_list) # output : [1, ‘O’, ’Welcome’]
Removing/Deleting elements from the List
• The pop() method removes and returns the last item if the index is not
provided. This helps us implement lists as stacks (first in, last out data
structure).
my_list.pop( )
print(my_list) # output : [1, ‘H’, 3.4, ‘O’]
Removing/Deleting elements from the List
• We can also use the clear() method to remove all the elements from a list.
my_list.clear( )
print(my_list) # output : [ ]
Update/Change List Elements
• Lists are mutable, meaning their elements can be changed unlike string or tuple.
• We can use the assignment operator = to change an item or a range of items.
• We can use + operator to combine two lists. This is also called concatenation.
• The * operator repeats a list for the given number of times.
• We can test if an item exists in a list or not, using the membership operator in and not in.
Output :
my_list = [1, 2, 3]
1
for x in my_list :
2
print(x)
3
Basic List Operations
my_list = [1, 2, 3]
print( len(my_list)) # output : 3
Python List Methods
• List comprehensions are used for creating new lists from other iterables like tuples,
strings, lists, etc.
• A list comprehension consists of an expression followed by for statement inside square
brackets.
• A tuple in Python is similar to a list. The difference between the two is that we cannot
change the elements of a tuple once it is assigned whereas we can change the elements of
a list.
• The important characteristics of Python Tuples are as follows:
1. Tuples are ordered.
2. Tuples can contain any arbitrary objects.
3. Tuples elements can be accessed by index.
4. Tuples can be nested.
5. Tuples are immutable.
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.).
# Empty tuple
my_tuple = ()
print(my_tuple) #output:( )
# nested tuple
my_tuple = (“Hello", [8, 4, 6], (1, 2, 3))
print(my_tuple) # output : (‘Hello', [8, 4, 6], (1, 2, 3))
• A tuple can also be created without using parentheses. This is known as tuple packing.
• The individual items are “unpacked” into the objects in the tuple. When unpacking, the
number of variables on the left must match the number of values in the tuple.
• Creating a tuple with one element is a bit tricky. Having one element within parentheses is
not enough. We will need a trailing comma to indicate that it is, in fact, a tuple.
my_tuple = ("hello")
print(type(my_tuple)) # output : <class 'str'>
# Parentheses is optional
my_tuple = "hello",
print(type(my_tuple)) # output:<class 'tuple'>
Accessing elements from the Tuple
# Tuple indexing
my_tuple = (1, 2, ’Hello’, 3.4, 5)
print(my_tuple[0]) # Output: 1
print(my_tuple[2]) # Output: Hello
print(my_tuple[4]) # Output: 5
print(my_tuple[4.0]) # error
print(my_tuple[6]) # IndexError: tuple index out of range
Accessing elements from the Tuple
• Python allows negative indexing for its sequences. The index of -1 refers to
the last item, -2 to the second last item and so on.
print(my_tuple[-1]) #output : N
print(my_tuple[-5]) #output : Y
Accessing elements from the Tuple
• We can access a range of items in a tuple by using the slicing operator :(colon).
• Tuples are immutable and hence they do not allow deletion of a part of it.
• Methods that add items or remove items are not available with tuple. Only the
following two methods are available.
Built-in-Method Description
my_tuple2 = (0,1,2,3,4,1,9,1,10)
print(my_tuple2.count(1)) # Output: 3
print(my_tuple2.index(9)) # Output: 6
Python Tuple Functions
a = 10
b = 20
print(f‘ Before swapping a : {a} , b : {b}’)
a, b = b, a
print(f‘ After swapping a : {a} , b : {b}’)
Advantages of Tuple over List
• 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. Using a tuple instead of a list guards data against accidental
modification.
Set in Python
• 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.
Creating a Set
Note : We can see that the resulting sets are unordered: the original order, as specified in the
definition, is not necessarily preserved. Additionally, duplicate values are only represented in
the set once.
Creating a Set
# set of integers
my_set = {1, 2, 3, 4}
print(my_set) #output: {1, 2, 3, 4}
• Set items cannot be accessed 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.
# set of integers
my_set = {1, 2, 3, 4}
for x in my_set :
print(x) #output: 1 2 3 4
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.
• Use built-in set functions add(), remove() or update() methods to modify set collection.
Adding Elements to a Set
• We can add a single element to set using the add() method.Loops are used to add multiple
elements at a time with the use of add() method.
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # output: {1, 2, 3, 4}
# Adding elements to the Set using Iterator
set1 = set( )
for i in range(1, 6) :
set1.add(i)
print(set1) #output : {1, 2, 3, 4, 5}
Adding Elements to a Set
• Multiple elements can be added using the update() method. The update() method can take
tuples, lists, strings or other sets as its argument. In all cases, duplicates are avoided.
# set of integers
my_set = {1,2,3}
my_set.update([3,4,5])
print(my_set) #output: {1, 2, 3, 4, 5}
• A particular item can be removed from a set using the methods discard() and remove().
# initialize my_set
my_set = {1, 2, 3, 4, 5, 6}
my_set.discard(4) # discard an element
print(my_set) #output: {1, 2, 3, 5, 6}
• The only difference between the two is that the discard() method leaves a set unchanged if
the element is not present in the set. On the other hand, the remove() method will raise an
error in such a condition (if element is not present in the set).
# initialize my_set
my_set = {1, 3, 5}
my_set.discard(2) # discard an element not present in my_set
print(my_set) #output: {1, 3, 5}
• pop() method can also be used to remove and return an element from the set, but it
removes only the last element of the set.
• Note – Since set is an unordered data type, there is no way of determining which item
will be popped. It is completely arbitrary.
# initialize set1
set1 = set(“Hello")
print(set1) #output: {'l', 'e', 'o', 'H'}
set1.pop( ) # pop random element
print(my_set) #output: {'e', 'o', 'l'}
Removing elements from a set
• We can also remove all the items from a set using the clear() method.
# initialize set1
set1 = {1,2,3}
set1.clear()
print(set1) #output: set( )
Python Set Operations
• Union: Returns a new set with elements from both the sets.
• 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 union()
method.
Set Union
# Intersection of sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
• Difference: Returns a set containing elements only in the first set, but not in the second
set.
• Difference of the set B from set A(A - B) is a set of elements that are only in A but not in B.
Similarly, B - A is a set of elements in B but not in A.
• Difference is performed using - operator. Same can be accomplished using the difference()
method.
Set Difference
# use - operator on A
print( A - B ) #output: {1, 2, 3}
# use - operator on B
print( B - A ) #output: {8, 6, 7}
Set Difference
• Symmetric Difference: Returns a set consisting of elements in both sets, excluding the
common elements.
• Symmetric Difference of A and B is a set of elements in A and B but not in both (excluding
the intersection).
• Symmetric difference is performed using ^ operator. Same can be accomplished using the
method symmetric_difference().
Set Symmetric Difference
# use ^ operator
print( A ^ B ) #output: {1, 2, 3, 6, 7, 8}
Set Symmetric Difference
Method Description
add() Adds an element to the set
intersection_update() Updates the set with the intersection of itself and another
Set Methods
Method Description
isdisjoint() Returns True if two sets have a null intersection
issubset() Returns True if another set contains this set
Removes and returns an arbitrary set element. Raises KeyError if the set is
pop()
empty
Removes an element from the set. If the element is not a member, raises a
remove()
KeyError
symmetric_difference_update() Updates a set with the symmetric difference of itself and another
update() Updates the set with the union of itself and others
Built-in Functions with Set
Function Description
all() Returns True if all elements of the set are true (or if the set is empty).
any() Returns True if any element of the set is true. If the set is empty, returns False.
Returns an enumerate object. It contains the index and value for all the items of the
enumerate()
set as a pair.
len() Returns the length (the number of items) in the set.
sorted() Returns a new sorted list from elements in the set(does not sort the set itself).
• Frozenset is a new class that has the characteristics of a set, but its elements cannot be
changed once assigned. While tuples are immutable lists, frozensets are immutable sets.
• Sets being mutable are unhashable, so they can't be used as dictionary keys. On the other
hand, frozensets are hashable and can be used as keys to a dictionary.
• Frozensets can be created using the frozenset() function.
• This data type supports methods like copy(), difference(), intersection(), isdisjoint(),
issubset(), issuperset(), symmetric_difference() and union(). Being immutable, it does not
have methods that add or remove elements.
Python Frozenset
# Frozensets
# initialize A and B
A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])
• As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier,
dictionaries are unordered.
• When we say that dictionaries are ordered, it means that the items have a defined
order, and that order will not change.
• Unordered means that the items does not have a defined order, you cannot refer to an
item by using an index.
Dictionary in Python
# empty dictionary
my_dict = { }
print(my_dict) #output: { }
my_dict = dict( )
print(my_dict) #output: { }
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
print(my_dict) #output: {1: 'apple', 2: 'ball'}
• While indexing is used with other data types to access values, a dictionary uses keys.
Keys can be used either inside square brackets [ ] or with the get() method.
• If we use the square brackets [ ], KeyError is raised in case a key is not found in the
dictionary. On the other hand, the get() method returns None if the key is not found.
Accessing Elements from Dictionary
• Dictionaries are mutable. We can add new items or change the value of existing items
using an assignment operator.
• If the key is already present, then the existing value gets updated. In case the key is not
present, a new (key: value) pair is added to the dictionary.
Changing and Adding Dictionary elements
# update value
my_dict['age'] = 27
print(my_dict) #output : {'name': 'Jack', 'age': 27}
# add item
my_dict[‘city'] = ‘Mumbai’
print(my_dict) #output : {'name': 'Jack', 'age': 27, 'city': 'Mumbai'}
• We can remove a particular item in a dictionary by using the pop() method. This
method removes an item with the provided key and returns the value.
• The popitem() method can be used to remove and return an arbitrary (key, value) item
pair from the dictionary.
• All the items can be removed at once, using the clear() method.
• We can also use the del keyword to remove individual items or the entire dictionary itself.
stud = {'name': 'Jack', 'age': 27, 'city': 'Mumbai', 'marks': {'phy': 78, 'chem': 90}}
del stud[‘marks’][‘phy’]
print(stud) # output : {'name': 'Jack', 'age': 27, 'city': 'Mumbai', 'marks': {'chem': 90}}
Basic Dictionary Operations
Method Description
clear() Removes all items from the dictionary.
Returns a new dictionary with keys from seq and value equal to v (defaults
fromkeys(seq[, v])
to None).
Returns the value of the key. If the key does not exist, returns d (defaults to
get(key[,d])
None).
items() Return a new object of the dictionary's items in (key, value) format.
Method Description
Removes the item with the key and returns its value or d if key is not found.
pop(key[,d])
If d is not provided and the key is not found, it raises KeyError.
Removes and returns an arbitrary item (key, value). Raises KeyError if the
popitem()
dictionary is empty.
Updates the dictionary with the key/value pairs from other, overwriting
update([other])
existing keys.
Method Description
Return True if all keys of the dictionary are True (or if the dictionary is
all()
empty).
Return True if any key of the dictionary is true. If the dictionary is empty,
any()
return False.