Python Chap3 (5)
Python Chap3 (5)
• Example
# Creating Blank List
List = []
print("Blank List: ")
print(List)
• Output
• Blank List:
[]
• Example • Example
# Creating a List of # Creating a List of
numbers strings and accessing
List = [10, 20, 14] # using index
print("\nList of numbers:
") List = ["Green",
"For", "Gorge"]
print(List)
• Output print("\nList Items: ")
• List of numbers: print(List[0])
[10, 20, 14] print(List[2])
• Output
List Items
Green
Gorge
• Example
# Creating a Multi-Dimensional List
# (By Nesting a list inside a List)
List = [['Green', 'For'] , ['Trees']]
print("\nMulti-Dimensional List: ")
print(List)
• Output
• Multi-Dimensional List:
[['Green', 'For'], ['Trees']]
• Accessing elements from the List • Example
• In order to access the list items refer to the #Creating a Multi-Dimensional
index number. Use the index operator [ ] to List
access an item in a list. The index must be an
integer. Nested lists are accessed using # (By Nesting a list inside a
nested indexing. List)
List = [['Green', 'For'] ,
• Example ['George']]
• List = ["Green", "For", print("Accessing a element from
"George"] a Multi-Dimensional list")
• print("Accessing a element from print(List[0][1])
the list")
print(List[1][0])
• print(List[0])
• print(List[2]) Output
• Output Accessing a element from a
• Accessing a element from the
Multi-Dimensional list
list For
• Green George
• Knowing the size of List
• Example
# Creating a List
List1 = []
print(len(List1))
• Output:
•0
3
• Adding Elements to a List
• Using append() method
Elements can be added to the List by using the built-in append() function. Only one element
at a time can be added to the list by using the append() method, for the addition of multiple
elements with the append() method, loops are used. Tuples can also be added to the list with
the use of the append method because tuples are immutable. Unlike Sets, Lists can also be
added to the existing list with the use of the append() method.
• Example
List = []
print("Initial blank List: ")
print(List)
• Output
Initial blank List:
[]
• Example 2
List.append(1)
List.append(2)
List.append(4)
print("\nList after Addition of Three elements: ")
print(List)
• output
List after Addition of Three elements:
[1, 2, 4]
# Addition of List to a List
List2 = ['Red', 'Green']
List.append(List2)
print("\nList after Addition of a List: ")
print(List)
• Output
• List after Addition of a List:
[1, 2, 4, ['Red', 'Green']]
• Using insert() method
• append() method only works for the addition of elements at the end of the
List, for the addition of elements at the desired position, insert() method is
used. Unlike append() which takes only one argument, the insert() method
requires two arguments(position, value).
# Creating a List
List = [1,2,3,4]
print("Initial List: ")
print(List)
• Output
• Initial List:
• [1, 2, 3, 4]
# Addition of Element at
# specific Position
# (using Insert Method)
List.insert(3, 12)
List.insert(0, 'Green')
print("\nList after performing Insert Operation: ")
print(List)
• output
• List after performing Insert Operation:
• ['Green', 1, 2, 3, 12, 4]
• Using extend() method
• Other than append() and insert() methods, there’s one more method for the Addition of elements,
extend(), this method is used to add multiple elements at the same time at the end of the list.
Note – append() and extend() methods can only add elements at the end.
• Example
# Creating a List
List = [1,2,3,4]
print("Initial List: ")
print(List)
List.extend([8, 'Green', 'Always'])
print("\nList after performing Extend Operation: ")
print(List)
• Output
• Initial List:
• [1, 2, 3, 4]
•
• List after performing Extend Operation:
• Removing Elements from the List
1. Using remove() method
• Elements can be removed from the List by using the built-in remove() function but an Error arises if the
element doesn’t exist in the set. Remove() method only removes one element at a time, to remove a range of
elements, the iterator is used. The remove() method removes the specified item.
• Note – Remove method in List will only remove the first occurrence of the searched element.
• Example
List = [1, 2, 3, 4, 5, 6,7, 8, 9, 10, 11, 12]
print("Initial List: ")
print(List)
List.remove(5)
List.remove(6)
print("\nList after Removal of two elements: ")
print(List)
• Output
• Initial List:
• [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
•
• List after Removal of two elements:
• Example
# Removing elements from List
# using iterator method
for i in range(1, 5):
List.remove(i)
print("\nList after Removing a range of elements: ")
print(List)
• output
• List after Removing a range of elements:
• [7, 8, 9, 10, 11, 12]
2.Using pop() method
• Pop() function can also be used to remove and return an element from the set, but by default it removes only the
last element of the set, to remove an element from a specific position of the List, the index of the element is
passed as an argument to the pop() method.
• Example
List = [1,2,3,4,5]
List.pop()
print("\nList after popping an element: ")
print(List)
List.pop(2)
print("\nList after popping a specific element: ")
print(List)
• Output
• List after popping an element:
• [1, 2, 3, 4]
•
• List after popping a specific element:
[1, 2, 4]
• List Comprehension
• List comprehensions are used for creating new lists from other iterables like
tuples, strings, arrays, lists, etc.
A list comprehension consists of brackets containing the expression, which is
executed for each element along with the for loop to iterate over each
element.
• Example
# comprehension in Python
# below list contains square of all
# odd numbers from range 1 to 10
odd_square = [x ** 2 for x in range(1, 11) if x % 2 == 1]
print (odd_square)
• Output:
[1, 9, 25, 49, 81]
List Methods
Function Description
reduce() apply a particular function passed in its argument to all of the list elements stores the
intermediate result and only returns the final summation value
ord() Returns an integer representing the Unicode code point of the given Unicode character
cmp() This function returns 1 if the first list is “greater” than the second list
any() return true if any element of the list is true. if the list is empty, return false
accumulate() apply a particular function passed in its argument to all of the list elements returns a
list containing the intermediate results
returns a list of the results after applying the given function to each item of
map()
a given iterable
This function can have any number of arguments but only one expression, which is
lambda() evaluated and returned.
Tuples
• A tuple in Python is similar to a list.
• A Tuple is immutable. we cannot change the elements of a tuple once it is
assigned whereas we can change the elements of a list.
• 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.).
• Examples • Output
• # Empty tuple • ()
• my_tuple = () • (1, 2, 3)
• print(my_tuple) • (1, 'Hello', 3.4)
• ('mouse', [8, 4, 6], (1, 2,
• # Tuple having integers 3))
• my_tuple = (1, 2, 3)
• print(my_tuple)
•
• # tuple with mixed
datatypes
• my_tuple = (1, "Hello",
3.4)
• print(my_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))
# Parentheses is optional
my_tuple = "hello",
print(type(my_tuple)) # <class 'tuple'>
<class 'str'>
<class 'tuple'>
• <class 'tuple'>
• A tuple can also be created without using parentheses. This is known as tuple
packing.
• Example
• my_tuple = 3, 4.6, "dog"
• print(my_tuple)
•
• # tuple unpacking is also possible
• a, b, c = my_tuple
• print(a)
• print(b)
print(c)
• Output
• (3, 4.6, 'dog')
•3
• 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.
Likewise, nested tuples are accessed using nested indexing, as shown in the example below.
# Accessing tuple elements using indexing
my_tuple = ('p','e','r','m','i','t')
print(my_tuple[0]) # 'p'
print(my_tuple[5]) # 't'
# 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
• p
• t
• s
• 4
• 2. Negative Indexing • 3. Slicing
• Python allows negative indexing • We can access a range of items in
for its sequences. a tuple by using the slicing
• The index of -1 refers to the last operator colon :
item, -2 to the second last item • my_tuple =
and so on. ('p','r','o','g','r','a
• Example ','m','i','z')
• my_tuple = ('p', 'e', 'r', 'm', •
'i', 't') • print(my_tuple[1:4])
• print(my_tuple[-1]) •
print(my_tuple[-6]) • print(my_tuple[:-7])
• Output • Output
•t • ('r', 'o', 'g')
p ('p', 'r')
• Changing a Tuple
• Unlike lists, tuples are immutable. But, if the element is itself a mutable data type like a list,
its nested items can be changed.
• We can also assign a tuple to different values (reassignment).
• Examples
• my_tuple = (4, 2, 3, [6, 5])
• my_tuple[1] = 9
• # This statement error as TypeError: 'tuple' object does not
support item assignment
my_tuple[3][0] = 9
print(my_tuple)
my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple)
• output
• (4, 2, 3, [9, 5])
• Deleting a Tuple
• As discussed above, we cannot change the elements in a tuple. It means that we cannot
delete or remove items from a tuple.
• Deleting a tuple entirely, however, is possible using the keyword del
• Example
• my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
• del my_tuple[3]
• # Above statement gives error as TypeError: 'tuple'
object doesn't support item deletion
• del my_tuple
print(my_tuple)
• Output
• Traceback (most recent call last):
• File "<string>", line 12, in <module>
NameError: name 'my_tuple' is not defined
• Finding Length of a Tuple
• Example
tuple2 = ('python', 'Prog')
print(len(tuple2))
• Output
2
• Example2
• a = set()
print(type(a))
• Output
<class 'set'>
• Methods for Sets
• Adding elements With add() method
• Insertion in set is done through set.add() function, if member is not present
and inserted where an appropriate record value is created to store in the hash
table.
• We can add a single element using the add() method
• print(my_set)
Error : Traceback (most
• recent call last):
• my_set.discard(4) File "<string>", line
28, in <module>
• print(my_set) KeyError: 2
• Removing using Clear() Method
• We can also remove all the items from a set using the clear() method.
• Example
s1={3,4,5}
s1.clear()
print(s1)
• Output
set()
• Python Set Operations
• Sets can be used to carry out mathematical set operations like union,
intersection, difference and symmetric difference. We can do this with
operators or methods.
• 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 union() method.
• Example 1 Union by using Operator
s1={2,3,4}
s2={4,5,6}
print(s1|s2)
• Output
{2, 3, 4, 5, 6}
• Example2 By using Union() Method
s1={2,3,4,9}
s2={4,5,6,7}
print(s1.union(s2))
• Output
{2, 3, 4, 5, 6, 7, 9}
• Set Intersection • Example1 By using
• Intersection of A and B is a set of intersection() Method
elements that are common in both s1={2,3,4,6,9}
the sets. s2={5,6,7}
• Intersection is performed print(s1.intersection(s2))
using & operator. Same can be
• Output
accomplished
using the intersection() metho {6}
d.
• Example1 By using operator &
s1={2,3,4,9}
s2={4,5,6,7}
print(s1&s2)
• Output
{4}
• Set Difference • Example 2
• Difference of the set B from set A (A - B) is a s1={1,2,3,4,5}
set of elements that are only in A but not in B.
s2={4,5,7,8}
Similarly, B - A is a set of elements in B but not
in A. print(s2-s1)
• Difference is performed using - operator. • Output
Same can be accomplished using {8, 7}
the difference() method. • Example3
• Example1
s1={1,2,3,4,5}
s1={1,2,3,4,5} s2={4,5,7,8}
s2={4,5,8} print(s1.difference(s2))
print(s1-s2) • Output
• Output
{1, 2, 3}
{1, 2, 3}
• Set Symmetric Difference • Example 2
• Symmetric Difference of A and B is a set of s1={1,2,3,4,5}
elements in A and B but not in both
(excluding the intersection). s2={4,5,7,8}
• Symmetric difference is performed print(s1.symmetric_difference(s2))
using ^ operator. Same can be • Output
accomplished using the {1, 2, 3, 7, 8}
method symmetric_difference().
• Example 1
• s1={1,2,3,4,5}
• s2={4,5,7,8}
• print(s1^s2)
• Output
• {1, 2, 3, 7, 8}
• Operators for Sets Operators Notes
s1 == s2 s1 is equivalent to s2
s1 != s2 s1 is not equivalent to s2
s1 <= s2 s1 is subset of s2
s1 >= s2 s1 is superset of s2
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 set as
enumerate()
a pair.
sorted() Returns a new sorted list from elements in the set(does not sort the set itself).
# using dict()
my_dict = dict({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.
•
• Examples
• Output
Jack
26
None
Traceback (most recent call last):
File "<string>", line 15, in <module>
print(my_dict['address'])
KeyError: 'address'
• Examples
Dict = {1: 'Green', 2: 'For', 3:{'A' : 'Welcome', 'B' :
'To', 'C' : 'Germany'}}
• print(Dict)
• OutPut
{1: 'Green', 2: 'For', 3: {'A': 'Welcome', 'B': 'To',
'C': 'Germany'}}
• Changing and Adding Dictionary elements
• 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.
• Example • Output
• my_dict = {'name': 'Jack', • {'name': 'Jack', 'age':
'age': 26} 27}
• {'name': 'Jack', 'age':
• my_dict['age'] = 27 27, 'address':
'Downtown'}
•
• print(my_dict)
•
• my_dict['address'] =
'Downtown'
print(my_dict)
• Removing elements from Dictionary
• 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.
Examples
• Output
squares = {1: 1, 2: 4, 3: • 16
9, 4: 16, 5: 25}
• {1: 1, 2: 4, 3: 9, 5:
25}
print(squares.pop(4)) • (5, 25)
• {1: 1, 2: 4, 3: 9}
print(squares) • {}
• Traceback (most recent
print(squares.popitem()) call last):
• File "<string>", line
30, in <module>
print(squares)
• print(squares)
NameError: name 'squares'
squares.clear()
is not defined
• Python Dictionary Comprehension
• Dictionary comprehension is an elegant and concise way to create a new dictionary from an
iterable in Python.
• Dictionary comprehension consists of an expression pair (key: value) followed by
a for statement inside curly braces {}.
• Here is an example to make a dictionary with each item being a pair of a number and its square.
• Example
• squares = {x: x*x for x in range(6)}
• print(squares)
This code is equivalent to
squares = {}
for x in range(6):
squares[x] = x*x
print(squares)
• Output
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
• Dictionary Membership Test
• We can test if a key is in a dictionary or not using the keyword in. Notice that the
membership test is only for the keys and not for the values.
• Example
• squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
•
• print(1 in squares)
•
• print(2 not in squares)
•
• print(49 in squares)
• Output
• True
• True
False
• Iterating Through a Dictionary
• We can iterate through each key in a dictionary using a for loop.
• Example
• squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
• for i in squares:
• print(squares[i])
• Output
•1
•9
• 25
• 49
81
• Python Dictionary Methods
Method Description
fromkeys(seq[, v]) Returns a new dictionary with keys from seq and value equal to v (defaults to None).
get(key[,d]) Returns the value of the key. If the key does not exist, returns d (defaults to None).
items() Return a new object of the dictionary's items in (key, value) format.
Removes the item with the key and returns its value or d if key is not found. If d is not provided and the key is not
pop(key[,d])
found, it raises KeyError.
popitem() Removes and returns an arbitrary item (key, value). Raises KeyError if the dictionary is empty.
Returns the corresponding value if the key is in the dictionary. If not, inserts the key with a value of d and returns d
setdefault(key[,d])
(defaults to None).
update([other]) Updates the dictionary with the key/value pairs from other, overwriting existing keys.
Function Description
all() Return True if all keys of the dictionary are True (or if the dictionary is empty).
any() Return True if any key of the dictionary is true. If the dictionary is empty, return False.
if (x % 2 == 0):
print("even")
else:
print("odd")
print(evenOdd.__doc__)
• Output
Function to check if the number is even or odd
• The return statement
• The function return statement is used to exit from a function and go back to the function caller
and return the specified value or data item to the caller.
• Syntax: return [expression_list]
• The return statement can consist of a variable, an expression, or a constant which is returned to
the end of the function execution. If none of the above is present with the return statement a
None object is returned.
• Example
def square_value(num):
"""This function returns the square
value of the entered number"""
return num**2
print(square_value(2))
print(square_value(-4))
• Output
• 4
16
• Creating a Function
• We can create a Python function using the def keyword.
• Calling a Function
• After creating a function we can call it by using the name of the function
followed by parenthesis containing parameters of that particular function.
• Example
def fun():
print("Welcome to Python World")
fun()
• Output
Welcome to Python World
• Arguments of a Function
• Arguments are the values passed inside the parenthesis of the function. A function can have any
number of arguments separated by a comma.
• Example: Python Function with arguments
• In this example, we will create a simple function to check whether the number passed as an
argument to the function is even or odd.
Example :
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
evenOdd(2)
evenOdd(3)
Output :
even
• Scope and Lifetime of variables
• Scope of a variable is the portion of a program where the variable is recognized. Parameters and
variables defined inside a function are not visible from outside the function. Hence, they have a local
scope.
• The lifetime of a variable is the period throughout which the variable exists in the memory. The
lifetime of variables inside a function is as long as the function executes.
• They are destroyed once we return from the function. Hence, a function does not remember the
value of a variable from its previous calls.
• Example
• def my_func():
• x = 10
• print("Value inside function:",x)
• x = 20
• my_func()
print("Value outside function:",x)
• Output
• Value inside function: 10
• Anonymous functions :
• In Python, an anonymous function means that a function is without a name.
As we already know the def keyword is used to define the normal functions
and the lambda keyword is used to create anonymous functions. Please see
this for details.
def cube(x): return x*x*x
cube_v2 = lambda x : x*x*x
print(cube(7))
print(cube_v2(7))
• Output
• 343
• Python Function within Functions
• A function that is defined inside another function is known as the inner function or
nested function. Nested functions are able to access variables of the enclosing
scope. Inner functions are used so that they can be protected from everything
happening outside the function.
• Example
def f1():
s = 'welcome'
def f2():
print(s)
f2()
f1()
• Output
welcome