SlideShare a Scribd company logo
1 of 118
Module 2
Lists, Tuples, Files
1
21MSIT4H02 – Python Programming
Master of Science in Computer Science & Information Technology
[MSc-CSIT]
• Operators are special symbols in Python that carry out
arithmetic or logical computation.
• The value that the operator operates on is called the operand.
For example:
>>> 2+3
5
Raghavendra R Assistant Professor School of CS & IT 2
Operators
Unit 2
Lists, Tuples,
Files
• Arithmetic operators are used to perform mathematical
operations like addition, subtraction, multiplication etc.
Raghavendra R Assistant Professor School of CS & IT 3
Arithmetic operators
Unit 2
Lists, Tuples,
Files
x = 15
y = 4
# Output: x + y = 19
print('x + y =',x+y)
# Output: x - y = 11
print('x - y =',x-y)
# Output: x * y = 60
print('x * y =',x*y)
# Output: x / y = 3.75
print('x / y =',x/y)
# Output: x // y = 3
print('x // y =',x//y)
# Output: x ** y = 50625
print('x ** y =',x**y)
Raghavendra R Assistant Professor School of CS & IT 4
Example #1: Arithmetic operators
Unit 2
Lists, Tuples,
Files
x + y = 19
x - y = 11
x * y = 60
x / y = 3.75
x // y = 3
x ** y = 50625
• Comparison operators are used to compare values.
• It either returns True or False according to the condition.
Raghavendra R Assistant Professor School of CS & IT 5
Comparison operators
Unit 2
Lists, Tuples,
Files
x = 10
y = 12
# Output: x > y is False
print('x > y is',x>y)
# Output: x < y is True
print('x < y is',x<y)
# Output: x == y is False
print('x == y is',x==y)
# Output: x != y is True
print('x != y is',x!=y)
# Output: x >= y is False
print('x >= y is',x>=y)
# Output: x <= y is True
print('x <= y is',x<=y)
Raghavendra R Assistant Professor School of CS & IT 6
Example #2: Comparison operators
Unit 2
Lists, Tuples,
Files
• Logical operators are the and, or, not operators.
• x = True
• y = False
• # Output: x and y is False
• print('x and y is',x and y)
• # Output: x or y is True
• print('x or y is',x or y)
• # Output: not x is False
• print('not x is',not x)
Raghavendra R Assistant Professor School of CS & IT 7
Logical operators
Unit 2
Lists, Tuples,
Files
• Bitwise operators act on operands as if they were string of binary digits. It
operates bit by bit, hence the name.
• For example, 2 is 10 in binary and 7 is 111.
• In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100
in binary)
Raghavendra R Assistant Professor School of CS & IT 8
Bitwise operators
Unit 2
Lists, Tuples,
Files
• Assignment operators are used in
Python to assign values to
variables.
• a = 5 is a simple assignment
operator that assigns the value 5 on
the right to the variable a on the
left.
• There are various compound
operators in Python like a += 5 that
adds to the variable and later
assigns the same. It is equivalent to
a = a + 5.
Raghavendra R Assistant Professor School of CS & IT 9
Assignment operators
Unit 2
Lists, Tuples,
Files
• Python language offers some special type of operators like the identity
operator or the membership operator.
• They are described below with examples.
Identity operators
• is and is not are the identity operators in Python.
• They are used to check if two values (or variables) are located on the same
part of the memory.
• Two variables that are equal does not imply that they are identical.
Raghavendra R Assistant Professor School of CS & IT 10
Special operators
Unit 2
Lists, Tuples,
Files
x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]
# Output: False
print(x1 is not y1)
# Output: True
print(x2 is y2)
# Output: False
print(x3 is y3)
Raghavendra R Assistant Professor School of CS & IT 11
Example #4: Identity operators
Unit 2
Lists, Tuples,
Files
Here, we see that x1 and y1 are integers of same
values, so they are equal as well as identical. Same
is the case with x2 and y2 (strings).
But x3 and y3 are list. They are equal but not
identical. It is because interpreter locates them
separately in memory although they are equal.
• in and not in are the membership operators in Python.
• They are used to test whether a value or variable is found in a
sequence (string, list, tuple, set and dictionary).
• In a dictionary we can only test for presence of key, not the
value.
Raghavendra R Assistant Professor School of CS & IT 12
Membership operators
Unit 2
Lists, Tuples,
Files
x = 'Hello world'
y = {1:'a',2:'b'}
# Output: True
print('H' in x)
# Output: True
print('hello' not in x)
# Output: True
print(1 in y)
# Output: False
print('a' in y)
Here, 'H' is in x but 'hello' is not present in x (remember, Python is case
sensitive). Similary, 1 is key and 'a' is the value in dictionary y. Hence, 'a' in y
returns False.
Raghavendra R Assistant Professor School of CS & IT 13
Unit 2
Lists, Tuples,
Files
• Python offers a range of compound datatypes often referred to as
sequences.
• List is one of the most frequently used and very versatile datatype used in
Python.
• In Python programming, a list is created by placing all the items (elements)
inside a square bracket [ ], separated by commas.
• It can have any number of items and they may be of different types
(integer, float, string etc.).
Raghavendra R Assistant Professor School of CS & IT 14
List
Unit 2
Lists, Tuples,
Files
# empty listmy_
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']]
append() - Add an element to the end of the list
extend() - Add all elements of a list to the another list
insert() - Insert an item at the defined index
remove() - Removes an item from the list
pop() - Removes and returns an element at the given index
clear() - Removes all items from the list
index() - Returns the index of the first matched item
count() - Returns the count of number of items passed as an argument
sort() - Sort items in a list in ascending order
reverse() - Reverse the order of items in the list
copy() - Returns a shallow copy of the list
Raghavendra R Assistant Professor School of CS & IT 15
List Methods
Unit 2
Lists, Tuples,
Files
• We can use the index operator [] to
access an item in a list.
• Index starts from 0.
• 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.
Raghavendra R Assistant Professor School of CS & IT 16
access elements from a list
Unit 2
Lists, Tuples,
Files
my_list = ['p','r','o','b','e']
# Output: p
print(my_list[0])
# Output: o
print(my_list[2])
# Output: e
print(my_list[4])
# Error! Only integer can be used for
indexing
# my_list[4.0]
# Nested List
n_list = ["Happy", [2,0,1,5]]
# Nested indexing
# Output: a
print(n_list[0][1])
# Output: 5
print(n_list[1][3])
• 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']
# Output: e
print(my_list[-1])
# Output: p
print(my_list[-5])
Raghavendra R Assistant Professor School of CS & IT 17
Negative indexing
Unit 2
Lists, Tuples,
Files
• We can access a range of items in a list by using the slicing
operator (colon).
my_list = ['p','r','o','g','r','a','m','i','z']
# elements 3rd to 5th
print(my_list[2:5])
# elements beginning to 4th
print(my_list[:-5])
# elements 6th to end
print(my_list[5:])
# elements beginning to end
print(my_list[:])
Raghavendra R Assistant Professor School of CS & IT 18
slice lists
Unit 2
Lists, Tuples,
Files
• We can use assignment operator (=) to change an item or a range of items.
# mistake values
odd = [2, 4, 6, 8]
# change the 1st item
odd[0] = 1
# Output: [1, 4, 6, 8]
print(odd)
# change 2nd to 4th items
odd[1:4] = [3, 5, 7]
# Output: [1, 3, 5, 7]
print(odd)
Raghavendra R Assistant Professor School of CS & IT 19
change or add elements to a
list
Unit 2
Lists, Tuples,
Files
• We can add one item to a list using append() method or add
several items using extend() method.
odd = [1, 3, 5]
odd.append(7)
# Output: [1, 3, 5, 7]
print(odd)
odd.extend([9, 11, 13])
# Output: [1, 3, 5, 7, 9, 11, 13]
print(odd)
Raghavendra R Assistant Professor School of CS & IT 20
change or add elements to
a list
Unit 2
Lists, Tuples,
Files
• We can also use + operator to combine two lists. This is also
called concatenation.
• The * operator repeats a list for the given number of times.
odd = [1, 3, 5]
# Output: [1, 3, 5, 9, 7, 5]
print(odd + [9, 7, 5])
#Output: ["re", "re", "re"]
print(["re"] * 3)
Raghavendra R Assistant Professor School of CS & IT 21
change or add elements to
a list
Unit 2
Lists, Tuples,
Files
Furthermore, we can insert one item at a desired location by
using the method insert() or insert multiple items by squeezing it
into an empty slice of a list.
odd = [1, 9]
odd.insert(1,3)
# Output: [1, 3, 9]
print(odd)
odd[2:2] = [5, 7]
# Output: [1, 3, 5, 7, 9]
print(odd)
Raghavendra R Assistant Professor School of CS & IT 22
change or add elements to
a list
Unit 2
Lists, Tuples,
Files
• We can delete one or more items from a list using the keyword del.
• It can even delete the list entirely.
my_list = ['p','r','o','b','l','e','m']
# delete one item
del my_list[2]
# Output: ['p', 'r', 'b', 'l', 'e', 'm']
print(my_list)
# delete multiple items
del my_list[1:5]
# Output: ['p', 'm']
print(my_list)
# delete entire list
del my_list
# Error: List not defined
print(my_list)
Raghavendra R Assistant Professor School of CS & IT 23
delete or remove elements
from a list
Unit 2
Lists, Tuples,
Files
• We can use remove() method to remove the given item or
pop() method to remove an item at the given index.
• The pop() method removes and returns the last item if index is
not provided.
• This helps us implement lists as stacks (first in, last out data
structure).
• We can also use the clear() method to empty a list.
Raghavendra R Assistant Professor School of CS & IT 24
delete or remove elements
from a list
Unit 2
Lists, Tuples,
Files
my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')
# Output: ['r', 'o', 'b', 'l', 'e', 'm']
print(my_list)
# Output: 'o'
print(my_list.pop(1))
# Output: ['r', 'b', 'l', 'e', 'm']
print(my_list)
# Output: 'm'
print(my_list.pop())
# Output: ['r', 'b', 'l', 'e']
print(my_list)
my_list.clear()
# Output: []
print(my_list)
Raghavendra R Assistant Professor School of CS & IT 25
delete or remove elements
from a list
Unit 2
Lists, Tuples,
Files
• Finally, we can also delete items in a list by assigning an
empty list to a slice of elements.
>>> my_list =['p','r','o','b','l','e','m']
>>> my_list[2:3] = []
>>> my_list
['p', 'r', 'b', 'l', 'e', 'm']
>>> my_list[2:5] = []
>>> my_list
['p', 'r', 'm']
Raghavendra R Assistant Professor School of CS & IT 26
delete or remove elements
from a list
Unit 2
Lists, Tuples,
Files
• List comprehension is an elegant and concise way to create a 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)]
# 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)
Raghavendra R Assistant Professor School of CS & IT 27
create new List
Unit 2
Lists, Tuples,
Files
• A list comprehension can optionally contain more for or if statements.
• An optional if statement 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']
Raghavendra R Assistant Professor School of CS & IT 28
Unit 2
Lists, Tuples,
Files
• The insert() method inserts an element to the list at a given index.
• The syntax of insert() method is
• list.insert(index, element)
• The insert() function takes two parameters:
• index - position where an element needs to be inserted
• element - this is the element to be inserted in the list
# vowel list
vowel = ['a', 'e', 'i', 'u']
# inserting element to list at 4th position
vowel.insert(3, 'o')
print('Updated List: ', vowel)
When you run the program, the output will be:
Updated List: ['a', 'e', 'i', 'o', 'u']
Raghavendra R Assistant Professor School of CS & IT 29
List insert()
Unit 2
Lists, Tuples,
Files
• The remove() method removes the first matching element
(which is passed as an argument) from the list.
• The syntax of the remove() method is:
list.remove(element)
remove() Parameters
• The remove() method takes a single element as an argument
and removes it from the list.
• If the element doesn't exist, it throws ValueError:
list.remove(x): x not in list exception.
Raghavendra R Assistant Professor School of CS & IT 30
List remove()
Unit 2
Lists, Tuples,
Files
# animals list
animals = ['cat', 'dog', 'rabbit', 'guinea pig']
# 'rabbit' is removed
animals.remove('rabbit')
# Updated animals List
print('Updated animals list: ', animals)
Output
Updated animals list: ['cat', 'dog', 'guinea pig']
Raghavendra R Assistant Professor School of CS & IT 31
Remove element from the list
Unit 2
Lists, Tuples,
Files
# animals list
animals = ['cat', 'dog', 'dog', 'rabbit', 'guinea pig‘, 'dog']
# ‘dog' is removed
animals.remove(‘dog')
# Updated animals List
print('Updated animals list: ', animals)
Output
Updated animals list: ['cat', 'dog', 'guinea pig‘, ‘dog’]
Here, only the first occurrence of element 'dog' is removed from
the list.
Raghavendra R Assistant Professor School of CS & IT 32
remove() method on a list
having duplicate elements
Unit 2
Lists, Tuples,
Files
• The index() method searches an element in the list and returns
its index.
• In simple terms, the index() method finds the given element in
a list and returns its position.
• If the same element is present more than once, the method
returns the index of the first occurrence of the element.
• Note: Index in Python starts from 0, not 1.
• The syntax of the index() method is:
list.index(element)
Raghavendra R Assistant Professor School of CS & IT 33
List index()
Unit 2
Lists, Tuples,
Files
# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']
# index of 'e'
index = vowels.index('e')
print('The index of e:', index)
# index of the first 'i'
index = vowels.index('i')
print('The index of i:', index)
Output
The index of e: 1
The index of i: 2
Raghavendra R Assistant Professor School of CS & IT 34
Find the position of an
element in the list
Unit 2
Lists, Tuples,
Files
# random list
random = ['a', ('a', 'b'), [3, 4]]
# index of ('a', 'b')
index = random.index(('a', 'b'))
print("The index of ('a', 'b'):", index)
# index of [3, 4]
index = random.index([3, 4])
print("The index of [3, 4]:", index)
Output
The index of ('a', 'b'): 1
The index of [3, 4]: 2
Raghavendra R Assistant Professor School of CS & IT 35
Find the index of tuple and
list inside a list
Unit 2
Lists, Tuples,
Files
• The count() method returns the number of occurrences of an
element in a list.
• In simple terms, count() method counts how many times an
element has occurred in a list and returns it.
• The syntax of count() method is:
list.count(element)
Raghavendra R Assistant Professor School of CS & IT 36
List count()
Unit 2
Lists, Tuples,
Files
# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']
# count element 'i'
count = vowels.count('i')
# print count
print('The count of i is:', count)
# count element 'p'
count = vowels.count('p')
# print count
print('The count of p is:', count)
When you run the program, the output will be:
The count of i is: 2
The count of p is: 0
Raghavendra R Assistant Professor School of CS & IT 37
Count the occurrence of an
element in the list
Unit 2
Lists, Tuples,
Files
# random list
random = ['a', ('a', 'b'), ('a', 'b'), [3, 4]]
# count element ('a', 'b')
count = random.count(('a', 'b'))
# print count
print("The count of ('a', 'b') is:", count)
# count element [3, 4]
count = random.count([3, 4])
# print count
print("The count of [3, 4] is:", count)
When you run the program, the output will be:
The count of ('a', 'b') is: 2
The count of [3, 4] is: 1
Raghavendra R Assistant Professor School of CS & IT 38
Count the occurrence of tuple
and list inside the list
Unit 2
Lists, Tuples,
Files
• The pop() method removes the item at the given index from
the list and returns the removed item.
• The syntax of the pop() method is:
list.pop(index)
pop() parameters
• The pop() method takes a single argument (index).
• The argument passed to the method is optional. If not passed,
the default index -1 is passed as an argument (index of the last
item).
• If the index passed to the method is not in range, it throws
IndexError: pop index out of range exception.
Raghavendra R Assistant Professor School of CS & IT 39
List pop()
Unit 2
Lists, Tuples,
Files
# programming languages list
languages = ['Python', 'Java', 'C++', 'French', 'C']
# remove and return the 4th item
return_value = languages.pop(3)
print('Return Value:', return_value)
# Updated List
print('Updated List:', languages)
Output
Return Value: French
Updated List: ['Python', 'Java', 'C++', 'C']
Raghavendra R Assistant Professor School of CS & IT 40
Pop item at the given index
from the list
Unit 2
Lists, Tuples,
Files
# programming languages list
languages = ['Python', 'Java', 'C++',
'Ruby', 'C']
# remove and return the last item
print('When index is not passed:')
print('Return Value:', languages.pop())
print('Updated List:', languages)
# remove and return the last item
print('nWhen -1 is passed:')
print('Return Value:', languages.pop(-
1))
print('Updated List:', languages)
# remove and return the third last item
print('nWhen -3 is passed:')
print('Return Value:', languages.pop(-
3))
print('Updated List:', languages)
Output
When index is not passed:
Return Value: C
Updated List: ['Python', 'Java', 'C++',
'Ruby']
When -1 is passed:
Return Value: Ruby
Updated List: ['Python', 'Java', 'C++']
When -3 is passed:
Return Value: Python
Updated List: ['Java', 'C++']
Raghavendra R Assistant Professor School of CS & IT 41
pop() without an index, and
for negative indices
Unit 2
Lists, Tuples,
Files
The reverse() method reverses the elements of a given list.
The syntax of reverse() method is:
list.reverse()
reverse() parameter
The reverse() function doesn't take any argument.
Raghavendra R Assistant Professor School of CS & IT 42
List reverse()
Unit 2
Lists, Tuples,
Files
# Operating System List
os = ['Windows', 'macOS', 'Linux']
print('Original List:', os)
# List Reverse
os.reverse()
# updated list
print('Updated List:', os)
When you run the program, the output will be:
Original List: ['Windows', 'macOS', 'Linux']
Updated List: ['Linux', 'macOS', 'Windows']
Raghavendra R Assistant Professor School of CS & IT 43
Reverse a List
Unit 2
Lists, Tuples,
Files
# Operating System List
os = ['Windows', 'macOS', 'Linux']
# Printing Elements in Reversed Order
for o in reversed(os):
print(o)
When you run the program, the output will be:
Linux
macOS
Windows
Raghavendra R Assistant Professor School of CS & IT 44
Accessing Individual Elements
in Reversed Order
Unit 2
Lists, Tuples,
Files
• The sort() method sorts the elements of a given list.
• The sort() method sorts the elements of a given list in a
specific order - Ascending or Descending.
• The syntax of sort() method is:
list.sort(key=..., reverse=...)
• Alternatively, you can also use Python's in-built function
sorted() for the same purpose.
sorted(list, key=..., reverse=...)
• Note: Simplest difference between sort() and sorted() is: sort()
doesn't return any value while, sorted() returns an iterable list.
Raghavendra R Assistant Professor School of CS & IT 45
List sort()
Unit 2
Lists, Tuples,
Files
# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']
# sort the vowels
vowels.sort()
# print vowels
print('Sorted list:', vowels)
When you run the program, the output will be:
Sorted list: ['a', 'e', 'i', 'o', 'u']
Raghavendra R Assistant Professor School of CS & IT 46
Sort a given list
Unit 2
Lists, Tuples,
Files
# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']
# sort the vowels
vowels.sort(reverse=True)
# print vowels
print('Sorted list (in Descending):', vowels)
When you run the program, the output will be:
Sorted list (in Descending): ['u', 'o', 'i', 'e', 'a']
Raghavendra R Assistant Professor School of CS & IT 47
Sort the list in Descending
order
Unit 2
Lists, Tuples,
Files
• Lists are ordered.
• Lists can contain any arbitrary objects.
• List elements can be accessed by index.
• Lists can be nested to arbitrary depth.
• Lists are mutable.
• Lists are dynamic.
Raghavendra R Assistant Professor School of CS & IT 48
Features of List
Unit 2
Lists, Tuples,
Files
• A list is not merely a collection of objects. It is an ordered collection of
objects.
• The order in which you specify the elements when you define a list is an
innate characteristic of that list and is maintained for that list’s lifetime.
• Lists that have the same elements in a different order are not the same:
>>> a = ['foo', 'bar', 'baz', 'qux']
>>> b = ['baz', 'qux', 'bar', 'foo']
>>> a == b
False
>>> a is b
False
>>> [1, 2, 3, 4] == [4, 1, 3, 2]
False
Raghavendra R Assistant Professor School of CS & IT 49
Lists are ordered.
Unit 2
Lists, Tuples,
Files
• A list can contain any assortment of objects. The elements of a
list can all be the same type:
• >>> a = [2, 4, 6, 8]
• >>> a
[2, 4, 6, 8]
Or the elements can be of varying types:
• >>> a = [21.42, 'foobar', 3, 4, 'bark', False, 3.14159]
• >>> a
[21.42, 'foobar', 3, 4, 'bark', False, 3.14159]
Raghavendra R Assistant Professor School of CS & IT 50
Lists can contain any arbitrary objects.
Unit 2
Lists, Tuples,
Files
Lists can even contain complex
objects, like functions, classes, and
modules, which you will learn.
>>> int
<class 'int'>
>>> len
<built-in function len>
>>> def foo():
... pass
...
>>> foo
<function foo at 0x035B9030>
>>> import math
>>> math
<module 'math' (built-in)>
>>> a = [int, len, foo, math]
>>> a
[<class 'int'>, <built-in function len>,
<function foo at 0x02CA2618>,
<module 'math' (built-in)>]
Raghavendra R Assistant Professor School of CS & IT 51
Unit 2
Lists, Tuples,
Files
A list can contain any number of objects, from zero to as many as your
computer’s memory will allow:
>>> a = []
>>> a
[]
>>> a = [ 'foo' ]
>>> a
['foo']
>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
... 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
... 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
... 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
... 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
Raghavendra R Assistant Professor School of CS & IT 52
Lists can be nested to arbitrary
depth
Unit 2
Lists, Tuples,
Files
• Individual elements in a list can be accessed using an index in
square brackets.
• This is exactly analogous to accessing individual characters in
a string.
• List indexing is zero-based as it is with strings.
Consider the following list:
>>>
>>> a = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
The indices for the elements in a are shown below:
Raghavendra R Assistant Professor School of CS & IT 53
List elements can be accessed by
index
Unit 2
Lists, Tuples,
Files
• The list is the first mutable data type you have encountered.
• Once a list has been created, elements can be added, deleted, shifted, and
moved around at will.
• Python provides a wide range of ways to modify lists.
A single value in a list can be replaced by indexing and simple assignment:
>>>
>>> a = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
>>> a
['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
>>> a[2] = 10
>>> a[-1] = 20
>>> a
['foo', 'bar', 10, 'qux', 'quux', 20]
Raghavendra R Assistant Professor School of CS & IT 54
Lists are mutable
Unit 2
Lists, Tuples,
Files
Modifying Multiple List Values
>>> a = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
>>> a[1:4]
['bar', 'baz', 'qux']
>>> a[1:4] = [1.1, 2.2, 3.3, 4.4, 5.5]
>>> a
['foo', 1.1, 2.2, 3.3, 4.4, 5.5, 'quux', 'corge']
>>> a[1:6]
[1.1, 2.2, 3.3, 4.4, 5.5]
>>> a[1:6] = ['Bark!']
>>> a
['foo', 'Bark!', 'quux', 'corge']
The number of elements inserted need not be equal to the number replaced.
Python just grows or shrinks the list as needed.
Raghavendra R Assistant Professor School of CS & IT 55
Unit 2
Lists, Tuples,
Files
>>> a = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
>>> a[2:2] = [1, 2, 3]
>>> a += [3.14159]
>>> a
['foo', 'bar', 1, 2, 3, 'baz', 'qux', 'quux', 'corge', 3.14159]
Similarly, a list shrinks to accommodate the removal of items:
>>> a = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
>>> a[2:3] = []
>>> del a[0]
>>> a
['bar', 'qux', 'quux', 'corge']
Raghavendra R Assistant Professor School of CS & IT 56
Lists are dynamic
Unit 2
Lists, Tuples,
Files
• 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.
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.).
Raghavendra R Assistant Professor School of CS & IT 57
Tuples
Unit 2
Lists, Tuples,
Files
# Empty tuple
my_tuple = ()
print(my_tuple)
# Tuple having integers
my_tuple = (1, 2, 3)
print(my_tuple)
# tuple with mixed datatypes
my_tuple = (1, "Hello", 3.4)
print(my_tuple)
# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
Raghavendra R Assistant Professor School of CS & IT 58
Tuples
Unit 2
Lists, Tuples,
Files
Create a Python Tuple With one Element
• In Python, 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 a tuple,
• var1 = ("Hello") # string
• var2 = ("Hello",) # tuple
• We can use the type() function to know which class a variable or a value
belongs to.
Raghavendra R Assistant Professor School of CS & IT 59
Tuples
Unit 2
Lists, Tuples,
Files
• Access Python Tuple Elements
• Like a list, each element of a tuple is represented by index numbers (0, 1,
...) where the first element is at index 0.
• We use the index number to access tuple elements. For example,
1. Indexing
• We can use the index operator [] to access an item in a tuple, where the
index starts from 0.
# accessing tuple elements using indexing
letters = ("p", "r", "o", "g", "r", "a", "m", "i", "z")
print(letters[0]) # prints "p"
print(letters[5]) # prints "a"
Raghavendra R Assistant Professor School of CS & IT 60
Tuples
Unit 2
Lists, Tuples,
Files
2. Negative Indexing
• Python allows negative indexing for its sequences.
• The index of -1 refers to the last item, -2 to the second last item and so on.
For example,
# accessing tuple elements using negative indexing
letters = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(letters[-1]) # prints 'z'
print(letters[-3]) # prints 'r'
Raghavendra R Assistant Professor School of CS & IT 61
Tuples
Unit 2
Lists, Tuples,
Files
3. Slicing
• We can access a range of items in a tuple by using the slicing operator
colon :.
# accessing tuple elements using slicing
my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
# elements 2nd to 4th index
print(my_tuple[1:4]) # prints ('r', 'o', 'g')
# elements beginning to 2nd
print(my_tuple[:-7]) # prints ('p', 'r')
# elements 8th to end
print(my_tuple[7:]) # prints ('i', 'z')
# elements beginning to end
print(my_tuple[:]) # Prints ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
Raghavendra R Assistant Professor School of CS & IT 62
Tuples
Unit 2
Lists, Tuples,
Files
• In Python ,methods that add items or remove items are not available with
tuple.
• Only the following two methods are available.
• Some examples of Python tuple methods:
my_tuple = ('a', 'p', 'p', 'l', 'e',)
print(my_tuple.count('p')) # prints 2
print(my_tuple.index('l')) # prints 3
• Here,
• my_tuple.count('p') - counts total number of 'p' in my_tuple
• my_tuple.index('l') - returns the first occurrence of 'l' in my_tuple
Raghavendra R Assistant Professor School of CS & IT 63
Tuples Methods
Unit 2
Lists, Tuples,
Files
Iterating through a Tuple
We can use the for loop to iterate over the elements of a tuple. For example,
languages = ('Python', 'Swift', 'C++')
# iterating through the tuple
for language in languages:
print(language)
Raghavendra R Assistant Professor School of CS & IT 64
Tuples
Unit 2
Lists, Tuples,
Files
Check if an Item Exists in the Tuple
• We use the in keyword to check if an item exists in the tuple or not. For
example,
languages = ('Python', 'Swift', 'C++')
print('C' in languages) # False
print('Python' in languages) # True
• Here,
• 'C' is not present in languages, 'C' in languages evaluates to False.
• 'Python' is present in languages, 'Python' in languages evaluates to True.
Raghavendra R Assistant Professor School of CS & IT 65
Tuples
Unit 2
Lists, Tuples,
Files
Raghavendra R Assistant Professor School of CS & IT 66
Tuples
Unit 2
Lists, Tuples,
Files
• A set is an unordered collection of items.
• Every element is unique (no duplicates) and must be immutable (which
cannot be changed).
• Sets can be used to perform mathematical set operations like union,
intersection, symmetric difference etc.
create a set
• A set is created by placing all the items (elements) inside curly braces {},
separated by comma or by using the built-in function set().
• It can have any number of items and they may be of different types
(integer, float, tuple, string etc.).
• But a set cannot have a mutable element, like list, set or dictionary, as its
element.
Raghavendra R Assistant Professor School of CS & IT 67
Sets
Unit 2
Lists, Tuples,
Files
# set do not have duplicates
# Output: {1, 2, 3, 4}
my_set = {1,2,3,4,3,2}
print(my_set)
# set cannot have mutable items
# here [3, 4] is a mutable list
# If you uncomment line #12,
# this will cause an error.
# TypeError: unhashable type:
'list'
#my_set = {1, 2, [3, 4]}
# we can make set from a list
# Output: {1, 2, 3}
my_set = set([1,2,3,2])
print(my_set)
Raghavendra R Assistant Professor School of CS & IT 68
Unit 2
Lists, Tuples,
Files
Creating an empty set is a bit tricky.
Empty curly braces {} will make an empty dictionary in Python. To make a set
without any elements we use the set() function without any argument.
# initialize a with {}
a = {}
# check data type of a
# Output: <class 'dict'>
print(type(a))
# initialize a with set()
a = set()
# check data type of a
# Output: <class 'set'>
print(type(a))
Raghavendra R Assistant Professor School of CS & IT 69
empty set
Unit 2
Lists, Tuples,
Files
• Sets are mutable. But since they are unordered, indexing have
no meaning.
• We cannot access or change an element of set using indexing
or slicing. Set does not support it.
• We can add single element using the add() method and
multiple elements using the update() method.
• The update() method can take tuples, lists, strings or other sets
as its argument. In all cases, duplicates are avoided.
Raghavendra R Assistant Professor School of CS & IT 70
change a set
Unit 2
Lists, Tuples,
Files
# initialize my_set
my_set = {1,3}
print(my_set)
# add an element
# Output: {1, 2, 3}
my_set.add(2)
print(my_set)
# add multiple elements
# Output: {1, 2, 3, 4}
my_set.update([2,3,4])
print(my_set)
# add list and set
# Output: {1, 2, 3, 4, 5, 6, 8}
my_set.update([4,5], {1,6,8})
print(my_set)
Raghavendra R Assistant Professor School of CS & IT 71
Unit 2
Lists, Tuples,
Files
• A particular item can be removed from set using methods,
discard() and remove().
• The only difference between the two is that, while using
discard() if the item does not exist in the set, it remains
unchanged.
• But remove() will raise an error in such condition.
Raghavendra R Assistant Professor School of CS & IT 72
remove elements
Unit 2
Lists, Tuples,
Files
# initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)
# discard an element
# Output: {1, 3, 5, 6}
my_set.discard(4)
print(my_set)
# remove an element
# Output: {1, 3, 5}
my_set.remove(6)
print(my_set)
# discard an element
# not present in my_set
# Output: {1, 3, 5}
my_set.discard(2)
print(my_set)
# remove an element
# not present in my_set
# If you uncomment line 27,
# you will get an error.
# Output: KeyError: 2
#my_set.remove(2)
Raghavendra R Assistant Professor School of CS & IT 73
Unit 2
Lists, Tuples,
Files
• 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.
• A = {1, 2, 3, 4, 5}
• B = {4, 5, 6, 7, 8}
Raghavendra R Assistant Professor School of CS & IT 74
Set Operations
Unit 2
Lists, Tuples,
Files
Set Union
Union of A and B is a set of all elements from both sets.
Union is performed using | operator. Same can be accomplished
using the method union().
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use | operator
# Output: {1, 2, 3, 4, 5, 6, 7, 8}
print(A | B)
Raghavendra R Assistant Professor School of CS & IT 75
Unit 2
Lists, Tuples,
Files
Set Intersection
• Intersection of A and B is a set of elements that are common in
both sets.
• Intersection is performed using & operator.
• Same can be accomplished using the method intersection().
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use & operator
# Output: {4, 5}
print(A & B)
Raghavendra R Assistant Professor School of CS & IT 76
Unit 2
Lists, Tuples,
Files
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()..
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use - operator on A
# Output: {1, 2, 3}
print(A - B)
Raghavendra R Assistant Professor School of CS & IT 77
Unit 2
Lists, Tuples,
Files
Set Symmetric Difference
• Symmetric Difference of A and B is a set of elements in both A
and B except those that are common in both.
• Symmetric difference is performed using ^ operator.
• Same can be accomplished using the method
symmetric_difference().
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use ^ operator
# Output: {1, 2, 3, 6, 7, 8}
print(A ^ B)
Raghavendra R Assistant Professor School of CS & IT 78
Unit 2
Lists, Tuples,
Files
Raghavendra R Assistant Professor School of CS & IT 79
Set Methods
Unit 2
Lists, Tuples,
Files
• We can test if an item exists in a set or not, using the keyword
in.
# initialize my_set
my_set = set("apple")
# check if 'a' is present
# Output: True
print('a' in my_set)
# check if 'p' is present
# Output: False
print('p' not in my_set)
Raghavendra R Assistant Professor School of CS & IT 80
Set Membership
Unit 2
Lists, Tuples,
Files
• Using a for loop, we can iterate though each item in a set.
>>> for letter in set("apple"):
... print(letter)
...
a
p
e
l
Raghavendra R Assistant Professor School of CS & IT 81
Iterating Through a Set
Unit 2
Lists, Tuples,
Files
Function Description
all() Return True if all elements of the set are true (or if the set is empty).
any()
Return True if any element of the set is true. If the set is empty,
return False.
enumerate()
Return an enumerate object. It contains the index and value of all the
items of set as a pair.
len() Return the length (the number of items) in the set.
max() Return the largest item in the set.
min() Return the smallest item in the set.
sorted()
Return a new sorted list from elements in the set(does not sort the set
itself).
sum() Return the sum of all elements in the set.
Raghavendra R Assistant Professor School of CS & IT 82
Built-in Functions with Set
Unit 2
Lists, Tuples,
Files
• A file object allows us to use, access and manipulate all the
user accessible files.
• One can read and write any such files.
• When a file operation fails for an I/O-related reason, the
exception IOError is raised.
• The first thing you’ll need to do is use Python’s built-
in open function to get a file object.
• The open function opens a file.
• When you use the open function, it returns something called
a file object.
• File objects contain methods and attributes that can be used to
collect information about the file you opened.
• They can also be used to manipulate said file.
Raghavendra R Assistant Professor School of CS & IT 83
File Objects
Unit 2
Lists, Tuples,
Files
• Python has in-built functions to create and manipulate files.
• The io module is the default module for accessing files and
you don't need to import it.
• The module consists of open(filename, access_mode) that
returns a file object, which is called "handle".
• You can use this handle to read from or write to a file.
• Python treats the file as an object, which has its own attributes
and methods.
file_object = open(“filename”, “mode”)
• where file_object is the variable to add the file object.
• mode – tells the interpreter and developer which way the file
will be used.
Raghavendra R Assistant Professor School of CS & IT 84
Unit 2
Lists, Tuples,
Files
`open(file, mode='r', buffering=-1, encoding=None, errors=None,
newline=None, closefd=True, opener=None)`
• file is an argument that you have to provide to the open function. All other
arguments are optional and have default values. Now, this argument is
basically the path where your file resides.
• If the path is in current working directory, you can just provide the
filename, just like in the following examples:
my_file_handle=open("mynewtextfile.txt")
• If the file resides in a directory other than that, you have to provide the full
path with the file name:
my_file_handle=open("D:new_diranotherfile.txt")
my_file_handle.read()
Raghavendra R Assistant Professor School of CS & IT 85
Unit 2
Lists, Tuples,
Files
Access Modes
• Access modes define in which way you want to open a file,
you want to open a file for read only, write only or for both.
• It specifies from where you want to start reading or writing in
the file.
• You specify the access mode of a file through
the mode argument.
• You use 'r', the default mode, to read the file.
• In other cases where you want to write or append, you
use 'w' or 'a', respectively.
Raghavendra R Assistant Professor School of CS & IT 86
Unit 2
Lists, Tuples,
Files
Character Function
r Open file for reading only. Starts reading from beginning of file. This default mode.
rb Open a file for reading only in binary format. Starts reading from beginning of file.
r+ Open file for reading and writing. File pointer placed at beginning of the file.
w
Open file for writing only. File pointer placed at beginning of the file. Overwrites
existing file and creates a new one if it does not exists.
wb Same as w but opens in binary mode.
w+ Same as w but also alows to read from file.
wb+ Same as wb but also alows to read from file.
a
Open a file for appending. Starts writing at the end of file. Creates a new file if file does
not exist.
ab Same as a but in binary format. Creates a new file if file does not exist.
a+ Same a a but also open for reading.
ab+ Same a ab but also open for reading.
Raghavendra R Assistant Professor School of CS & IT 87
Unit 2
Lists, Tuples,
Files
Python Method
• Method is called by its name, but it is associated to an
object (dependent).
• A method is implicitly passed the object on which it is
invoked.
• It may or may not return any data.
• A method can operate on the data (instance variables) that
is contained by the corresponding class.
Raghavendra R Assistant Professor School of CS & IT 88
Difference between
Method and Function
Unit 2
Lists, Tuples,
Files
# Python 3 User-Defined Method
class ABC :
def method_abc (self):
print("I am in method_abc of ABC class. ")
class_ref = ABC() # object of ABC class
class_ref.method_abc()
Raghavendra R Assistant Professor School of CS & IT 89
Unit 2
Lists, Tuples,
Files
Functions
• Function is block of code that is also called by its name.
(independent)
• The function can have different parameters or may not have
any at all. If any data (parameters) are passed, they
are passed explicitly.
• It may or may not return any data.
• Function does not deal with Class and its instance concept.
Raghavendra R Assistant Professor School of CS & IT 90
Unit 2
Lists, Tuples,
Files
def Subtract (a, b):
return (a-b)
print( Subtract(10, 12) ) # prints -2
print( Subtract(15, 6) ) # prints 9
**************************
s = sum([5, 15, 2])
print( s ) # prints 22
mx = max(15, 6)
print( mx ) # prints 15
Raghavendra R Assistant Professor School of CS & IT 91
Unit 2
Lists, Tuples,
Files
Method Description
close() Close an open file. It has no effect if the file is already closed.
detach()
Separate the underlying binary buffer from the TextIOBase and
return it.
fileno() Return an integer number (file descriptor) of the file.
flush() Flush the write buffer of the file stream.
isatty() Return True if the file stream is interactive.
read(n)
Read atmost n characters form the file. Reads till end of file if
it is negative or None.
readable() Returns True if the file stream can be read from.
readline(n=-1)
Read and return one line from the file. Reads in at most n bytes
if specified.
Raghavendra R Assistant Professor School of CS & IT 92
File Built-in Methods
Unit 2
Lists, Tuples,
Files
Method Description
readlines(n=-1)
Read and return a list of lines from the file. Reads in at
most n bytes/characters if specified.
seek(offset,from=SE
EK_SET)
Change the file position to offset bytes, in reference to from (start,
current, end).
seekable() Returns True if the file stream supports random access.
tell() Returns the current file location.
truncate(size=None)
Resize the file stream to size bytes. If size is not specified, resize to
current location.
writable() Returns True if the file stream can be written to.
write(s)
Write string s to the file and return the number of characters
written.
writelines(lines) Write a list of lines to the file.
Raghavendra R Assistant Professor School of CS & IT 93
File Built-in Methods
Unit 2
Lists, Tuples,
Files
closed: returns a boolean indicating the current state of the file
object.
It returns true if the file is closed and false when the file is open.
encoding: The encoding that this file uses.
When Unicode strings are written to a file, they will be converted
to byte strings using this encoding.
mode: The I/O mode for the file. If the file was created using the
open() built-in function, this will be the value of the mode
parameter.
Raghavendra R Assistant Professor School of CS & IT 94
File Built-in Attributes
Unit 2
Lists, Tuples,
Files
name: If the file object was created using open(), the name of the
file.
newlines: A file object that has been opened in universal newline
mode have this attribute which reflects the newline convention
used in the file.
The value for this attribute are “r”, “n”, “rn”, None or a tuple
containing all the newline types seen.
softspace: It is a boolean that indicates whether a space character
needs to be printed before another value when using the print
statement
Raghavendra R Assistant Professor School of CS & IT 95
File Built-in Attributes
Unit 2
Lists, Tuples,
Files
• f = open(__file__, 'a+')
• print(f.closed)
• print(f.encoding)
• print(f.mode)
• print(f.newlines)
• print(f.softspace)
Raghavendra R Assistant Professor School of CS & IT 96
File Built-in Attributes
Unit 2
Lists, Tuples,
Files
• There are many options to read python command line
arguments. The three most common ones are:
• Python sys.argv
• Python getopt module
• Python argparse module
Raghavendra R Assistant Professor School of CS & IT 97
Command Line Arguments
Unit 2
Lists, Tuples,
Files
• Python sys module stores the command line arguments into a list, we can
access it using sys.argv.
• This is very useful and simple way to read command line arguments as
String.
• Let’s look at a simple example to read and print command line arguments
using python sys module.
• Below image illustrates the output of a sample run of above program.
Raghavendra R Assistant Professor School of CS & IT 98
sys.argv module
Unit 2
Lists, Tuples,
Files
• Python getopt module is very similar in working as the
C getopt() function for parsing command-line parameters.
• Python getopt module is useful in parsing command line
arguments where we want user to enter some options too.
• Let’s look at a simple example to understand this.
Raghavendra R Assistant Professor School of CS & IT 99
getopt module
Unit 2
Lists, Tuples,
Files
Above example is very simple, but we can easily extend it to do
various things.
For example, if help option is passed then print some user
friendly message and exit. Here getopt module will automatically
parse the option value and map them. Below image shows a
sample run.
Raghavendra R Assistant Professor School of CS & IT 100
Unit 2
Lists, Tuples,
Files
• Python argparse module is the preferred way to parse
command line arguments.
• It provides a lot of option such as positional arguments, default
value for arguments, help message, specifying data type of
argument etc.
• At the very simplest form, we can use it like below.
Raghavendra R Assistant Professor School of CS & IT 101
argparse module
Unit 2
Lists, Tuples,
Files
Below is the output from quick run of above script.
Raghavendra R Assistant Professor School of CS & IT 102
Unit 2
Lists, Tuples,
Files
Recursing Through Directories
• In some situations you may need to recurse through directory
after directory. This could be for any number of reasons.
• In this example let’s look at how we can walk through a
directory and retrieve the names of all the files:
# This will walk through EVERY file in your computer
import os
# You can change the "/" to a directory of your choice
for file in os.walk("/"):
print(file)
Raghavendra R Assistant Professor School of CS & IT 103
File system
Unit 2
Lists, Tuples,
Files
• Being able to discern whether something is a file or directory
can come in handy.
• Let’s look at how you can check whether something is either a
file or directory in Python.
• To do this we can use the os.path.isfile() function which
returns False if it’s a directory or True if it is indeed a file.
>>> import os
>>> os.path.isfile("/")
False
>>> os.path.isfile("./main.py")
True
Raghavendra R Assistant Professor School of CS & IT 104
File system
Unit 2
Lists, Tuples,
Files
Checking if a File or Directory Exists
• If you wanted to check whether something exists on your
current machine you can use the os.path.exists() function,
passing in the file or directory you wish to check:
>>> import os
>>> os.path.exists("./main.py")
True
>>> os.path.exists("./dud.py")
False
Raghavendra R Assistant Professor School of CS & IT 105
File system
Unit 2
Lists, Tuples,
Files
Creating Directories in Python
• Say you not only wanted to traverse directories but also wished to create
your own. Well fear not, this is very possible using
the os.makedirs() function.
if not os.path.exists('my_dir'):
os.makedirs('my_dir')
• This will first go ahead and check to see if the directory my_dir exists, if it
doesn’t exist then it will go ahead and call the os.makedirs('my_dir') in
order to create our new directory for us.
• It should be noted that this could potentially cause issues.
• If you were to create the directory after checking that the directory doesn’t
exist somewhere else, before your call to os.makedirs('my_dir') executes,
you could see an OSError thrown.
Raghavendra R Assistant Professor School of CS & IT 106
File system
Unit 2
Lists, Tuples,
Files
• For the most part however you should be ok using the method
mentioned above.
• If you want to be extra careful and catch any potential
exceptions then you can wrap you call
to os.makedirs('my_dir') in a try...except like so:
if not os.path.exists('my_dir'):
try:
os.makedirs('my_dir')
except OSError as e:
if e.errno != errno.EEXIST:
raise
Raghavendra R Assistant Professor School of CS & IT 107
File system
Unit 2
Lists, Tuples,
Files
• File handling is basically the management of the files on a file
system.
• Every operating system has its own way to store files.
• Python File handling is useful to work with files in our
programs.
• We don’t have to worry about the underlying operating system
and its file system rules and operations.
Raghavendra R Assistant Professor School of CS & IT 108
File Handling
Unit 2
Lists, Tuples,
Files
Raghavendra R Assistant Professor School of CS & IT 109
Unit 2
Lists, Tuples,
Files
1
2
3
4
5
6
7
demo_file = open('Demo.txt', 'r')
# This statement will print every line in the file
for x in demo_file:
print (x)
# close the file, very important
demo_file.close()
Raghavendra R Assistant Professor School of CS & IT 110
Unit 2
Lists, Tuples,
Files
open() function
The open() function is used to open a file in a particular mode.
It basically creates a file object which can be used for further manipulations.
Syntax:
open(file_name, mode)
Different modes for opening a file:
•r: Read
•w: Write
•a: Append
•r+: Read and Write
Initially, we need to create a file and place it in the same directory as of the script.
Demo.txt
Welcome to the programming world!
Execute_file.py
Output:
Welcome to the programming world!
Here, the Execute_file.py script opens the Demo.txt file and prints the entire content
line-by-line.
read() function
The read() function is used to read the contents of the file. To
achieve the same, we need to open a file in the read mode.
demo_file = open("Demo.txt", "r")
print(demo_file.read())
demo_file.close()
Output:
Welcome to the programming world!
Raghavendra R Assistant Professor School of CS & IT 111
Unit 2
Lists, Tuples,
Files
write() function
The write() function is used to write to a file and make changes to
it.
demo_file = open('Demo.txt','w')
demo_file.write("Hello Everyone!.n")
demo_file.write("Engineering Discipline.")
demo_file.close()
Output: When we open the Demo.txt file, we can see the changes
reflected here.
Hello Everyone!.
Engineering Discipline.
Raghavendra R Assistant Professor School of CS & IT 112
Unit 2
Lists, Tuples,
Files
append() function
demo_file = open('Demo.txt','a')
demo_file.write("nStatement added to the end of the file..")
demo_file.close()
Output:
Hello Everyone!.
Engineering Discipline.
Statement added to the end of the file..
Raghavendra R Assistant Professor School of CS & IT 113
Unit 2
Lists, Tuples,
Files
split() function
The split() function is used to split lines within a file.
It splits up as soon as it encounters space in the script.
Demo.txt
Hello Everyone!.
Engineering Discipline.
Statement added to the end of the file..
Execute_file.py
Raghavendra R Assistant Professor School of CS & IT 114
Unit 2
Lists, Tuples,
Files
with open("Demo.txt", "r") as demo_file:
demo_data = demo_file.readlines()
for line in demo_data:
result = line.split()
print(result)
Output:
['Hello', 'Everyone!.']
['Engineering', 'Discipline.']
['Statement', 'added', 'to', 'the', 'end', 'of', 'the', 'file..']
Raghavendra R Assistant Professor School of CS & IT 115
Unit 2
Lists, Tuples,
Files
close() function
• The close() function is used to close a particular file post
manipulations on it.
• After writing to a file, if we do not call the close() method, all
the data written to the file will not be saved in it.
• It’s always a good idea to close the file after we are done with
it to release the resources.
Syntax:
file-name.close()
Raghavendra R Assistant Professor School of CS & IT 116
Unit 2
Lists, Tuples,
Files
rename() function
• The os module provides the rename() method to change the
name of the particular file.
Syntax:
os.rename(current_name,new_name)
Raghavendra R Assistant Professor School of CS & IT 117
Unit 2
Lists, Tuples,
Files
remove() method
• The os module provides the remove() method to delete the file
given as input.
import os
os.remove('Demo.txt')
Before executing the remove() method..
Raghavendra R Assistant Professor School of CS & IT 118
Unit 2
Lists, Tuples,
Files
Output: After executing the remove() method

More Related Content

Similar to Module 2 - Lists, Tuples, Files.pptx

Python lab basics
Python lab basicsPython lab basics
Python lab basicsAbi_Kasi
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdfNehaSpillai1
 
Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdfNehaSpillai1
 
Learn python - for beginners - part-2
Learn python - for beginners - part-2Learn python - for beginners - part-2
Learn python - for beginners - part-2RajKumar Rampelli
 
Python Unit 5 Questions n Notes.pdf
Python Unit 5 Questions n Notes.pdfPython Unit 5 Questions n Notes.pdf
Python Unit 5 Questions n Notes.pdfMCCMOTOR
 
Python elements list you can study .pdf
Python elements list you can study  .pdfPython elements list you can study  .pdf
Python elements list you can study .pdfAUNGHTET61
 
File handling in pythan.pptx
File handling in pythan.pptxFile handling in pythan.pptx
File handling in pythan.pptxNawalKishore38
 
Parts of python programming language
Parts of python programming languageParts of python programming language
Parts of python programming languageMegha V
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxMihirDatir
 
Revision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docRevision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docSrikrishnaVundavalli
 
‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptxRamiHarrathi1
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptxssuser8e50d8
 
02 Python Data Structure.pptx
02 Python Data Structure.pptx02 Python Data Structure.pptx
02 Python Data Structure.pptxssuser88c564
 
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptxRANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptxOut Cast
 

Similar to Module 2 - Lists, Tuples, Files.pptx (20)

Python lab basics
Python lab basicsPython lab basics
Python lab basics
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdf
 
Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdf
 
Python Session - 3
Python Session - 3Python Session - 3
Python Session - 3
 
Learn python - for beginners - part-2
Learn python - for beginners - part-2Learn python - for beginners - part-2
Learn python - for beginners - part-2
 
Python Unit 5 Questions n Notes.pdf
Python Unit 5 Questions n Notes.pdfPython Unit 5 Questions n Notes.pdf
Python Unit 5 Questions n Notes.pdf
 
Python elements list you can study .pdf
Python elements list you can study  .pdfPython elements list you can study  .pdf
Python elements list you can study .pdf
 
File handling in pythan.pptx
File handling in pythan.pptxFile handling in pythan.pptx
File handling in pythan.pptx
 
Python
PythonPython
Python
 
Parts of python programming language
Parts of python programming languageParts of python programming language
Parts of python programming language
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptx
 
Revision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docRevision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.doc
 
‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
 
Python_IoT.pptx
Python_IoT.pptxPython_IoT.pptx
Python_IoT.pptx
 
Python lists
Python listsPython lists
Python lists
 
Python lecture 05
Python lecture 05Python lecture 05
Python lecture 05
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptx
 
02 Python Data Structure.pptx
02 Python Data Structure.pptx02 Python Data Structure.pptx
02 Python Data Structure.pptx
 
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptxRANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
 

Recently uploaded

Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 

Recently uploaded (20)

Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 

Module 2 - Lists, Tuples, Files.pptx

  • 1. Module 2 Lists, Tuples, Files 1 21MSIT4H02 – Python Programming Master of Science in Computer Science & Information Technology [MSc-CSIT]
  • 2. • Operators are special symbols in Python that carry out arithmetic or logical computation. • The value that the operator operates on is called the operand. For example: >>> 2+3 5 Raghavendra R Assistant Professor School of CS & IT 2 Operators Unit 2 Lists, Tuples, Files
  • 3. • Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication etc. Raghavendra R Assistant Professor School of CS & IT 3 Arithmetic operators Unit 2 Lists, Tuples, Files
  • 4. x = 15 y = 4 # Output: x + y = 19 print('x + y =',x+y) # Output: x - y = 11 print('x - y =',x-y) # Output: x * y = 60 print('x * y =',x*y) # Output: x / y = 3.75 print('x / y =',x/y) # Output: x // y = 3 print('x // y =',x//y) # Output: x ** y = 50625 print('x ** y =',x**y) Raghavendra R Assistant Professor School of CS & IT 4 Example #1: Arithmetic operators Unit 2 Lists, Tuples, Files x + y = 19 x - y = 11 x * y = 60 x / y = 3.75 x // y = 3 x ** y = 50625
  • 5. • Comparison operators are used to compare values. • It either returns True or False according to the condition. Raghavendra R Assistant Professor School of CS & IT 5 Comparison operators Unit 2 Lists, Tuples, Files
  • 6. x = 10 y = 12 # Output: x > y is False print('x > y is',x>y) # Output: x < y is True print('x < y is',x<y) # Output: x == y is False print('x == y is',x==y) # Output: x != y is True print('x != y is',x!=y) # Output: x >= y is False print('x >= y is',x>=y) # Output: x <= y is True print('x <= y is',x<=y) Raghavendra R Assistant Professor School of CS & IT 6 Example #2: Comparison operators Unit 2 Lists, Tuples, Files
  • 7. • Logical operators are the and, or, not operators. • x = True • y = False • # Output: x and y is False • print('x and y is',x and y) • # Output: x or y is True • print('x or y is',x or y) • # Output: not x is False • print('not x is',not x) Raghavendra R Assistant Professor School of CS & IT 7 Logical operators Unit 2 Lists, Tuples, Files
  • 8. • Bitwise operators act on operands as if they were string of binary digits. It operates bit by bit, hence the name. • For example, 2 is 10 in binary and 7 is 111. • In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary) Raghavendra R Assistant Professor School of CS & IT 8 Bitwise operators Unit 2 Lists, Tuples, Files
  • 9. • Assignment operators are used in Python to assign values to variables. • a = 5 is a simple assignment operator that assigns the value 5 on the right to the variable a on the left. • There are various compound operators in Python like a += 5 that adds to the variable and later assigns the same. It is equivalent to a = a + 5. Raghavendra R Assistant Professor School of CS & IT 9 Assignment operators Unit 2 Lists, Tuples, Files
  • 10. • Python language offers some special type of operators like the identity operator or the membership operator. • They are described below with examples. Identity operators • is and is not are the identity operators in Python. • They are used to check if two values (or variables) are located on the same part of the memory. • Two variables that are equal does not imply that they are identical. Raghavendra R Assistant Professor School of CS & IT 10 Special operators Unit 2 Lists, Tuples, Files
  • 11. x1 = 5 y1 = 5 x2 = 'Hello' y2 = 'Hello' x3 = [1,2,3] y3 = [1,2,3] # Output: False print(x1 is not y1) # Output: True print(x2 is y2) # Output: False print(x3 is y3) Raghavendra R Assistant Professor School of CS & IT 11 Example #4: Identity operators Unit 2 Lists, Tuples, Files Here, we see that x1 and y1 are integers of same values, so they are equal as well as identical. Same is the case with x2 and y2 (strings). But x3 and y3 are list. They are equal but not identical. It is because interpreter locates them separately in memory although they are equal.
  • 12. • in and not in are the membership operators in Python. • They are used to test whether a value or variable is found in a sequence (string, list, tuple, set and dictionary). • In a dictionary we can only test for presence of key, not the value. Raghavendra R Assistant Professor School of CS & IT 12 Membership operators Unit 2 Lists, Tuples, Files
  • 13. x = 'Hello world' y = {1:'a',2:'b'} # Output: True print('H' in x) # Output: True print('hello' not in x) # Output: True print(1 in y) # Output: False print('a' in y) Here, 'H' is in x but 'hello' is not present in x (remember, Python is case sensitive). Similary, 1 is key and 'a' is the value in dictionary y. Hence, 'a' in y returns False. Raghavendra R Assistant Professor School of CS & IT 13 Unit 2 Lists, Tuples, Files
  • 14. • Python offers a range of compound datatypes often referred to as sequences. • List is one of the most frequently used and very versatile datatype used in Python. • In Python programming, a list is created by placing all the items (elements) inside a square bracket [ ], separated by commas. • It can have any number of items and they may be of different types (integer, float, string etc.). Raghavendra R Assistant Professor School of CS & IT 14 List Unit 2 Lists, Tuples, Files # empty listmy_ 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']]
  • 15. append() - Add an element to the end of the list extend() - Add all elements of a list to the another list insert() - Insert an item at the defined index remove() - Removes an item from the list pop() - Removes and returns an element at the given index clear() - Removes all items from the list index() - Returns the index of the first matched item count() - Returns the count of number of items passed as an argument sort() - Sort items in a list in ascending order reverse() - Reverse the order of items in the list copy() - Returns a shallow copy of the list Raghavendra R Assistant Professor School of CS & IT 15 List Methods Unit 2 Lists, Tuples, Files
  • 16. • We can use the index operator [] to access an item in a list. • Index starts from 0. • 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. Raghavendra R Assistant Professor School of CS & IT 16 access elements from a list Unit 2 Lists, Tuples, Files my_list = ['p','r','o','b','e'] # Output: p print(my_list[0]) # Output: o print(my_list[2]) # Output: e print(my_list[4]) # Error! Only integer can be used for indexing # my_list[4.0] # Nested List n_list = ["Happy", [2,0,1,5]] # Nested indexing # Output: a print(n_list[0][1]) # Output: 5 print(n_list[1][3])
  • 17. • 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'] # Output: e print(my_list[-1]) # Output: p print(my_list[-5]) Raghavendra R Assistant Professor School of CS & IT 17 Negative indexing Unit 2 Lists, Tuples, Files
  • 18. • We can access a range of items in a list by using the slicing operator (colon). my_list = ['p','r','o','g','r','a','m','i','z'] # elements 3rd to 5th print(my_list[2:5]) # elements beginning to 4th print(my_list[:-5]) # elements 6th to end print(my_list[5:]) # elements beginning to end print(my_list[:]) Raghavendra R Assistant Professor School of CS & IT 18 slice lists Unit 2 Lists, Tuples, Files
  • 19. • We can use assignment operator (=) to change an item or a range of items. # mistake values odd = [2, 4, 6, 8] # change the 1st item odd[0] = 1 # Output: [1, 4, 6, 8] print(odd) # change 2nd to 4th items odd[1:4] = [3, 5, 7] # Output: [1, 3, 5, 7] print(odd) Raghavendra R Assistant Professor School of CS & IT 19 change or add elements to a list Unit 2 Lists, Tuples, Files
  • 20. • We can add one item to a list using append() method or add several items using extend() method. odd = [1, 3, 5] odd.append(7) # Output: [1, 3, 5, 7] print(odd) odd.extend([9, 11, 13]) # Output: [1, 3, 5, 7, 9, 11, 13] print(odd) Raghavendra R Assistant Professor School of CS & IT 20 change or add elements to a list Unit 2 Lists, Tuples, Files
  • 21. • We can also use + operator to combine two lists. This is also called concatenation. • The * operator repeats a list for the given number of times. odd = [1, 3, 5] # Output: [1, 3, 5, 9, 7, 5] print(odd + [9, 7, 5]) #Output: ["re", "re", "re"] print(["re"] * 3) Raghavendra R Assistant Professor School of CS & IT 21 change or add elements to a list Unit 2 Lists, Tuples, Files
  • 22. Furthermore, we can insert one item at a desired location by using the method insert() or insert multiple items by squeezing it into an empty slice of a list. odd = [1, 9] odd.insert(1,3) # Output: [1, 3, 9] print(odd) odd[2:2] = [5, 7] # Output: [1, 3, 5, 7, 9] print(odd) Raghavendra R Assistant Professor School of CS & IT 22 change or add elements to a list Unit 2 Lists, Tuples, Files
  • 23. • We can delete one or more items from a list using the keyword del. • It can even delete the list entirely. my_list = ['p','r','o','b','l','e','m'] # delete one item del my_list[2] # Output: ['p', 'r', 'b', 'l', 'e', 'm'] print(my_list) # delete multiple items del my_list[1:5] # Output: ['p', 'm'] print(my_list) # delete entire list del my_list # Error: List not defined print(my_list) Raghavendra R Assistant Professor School of CS & IT 23 delete or remove elements from a list Unit 2 Lists, Tuples, Files
  • 24. • We can use remove() method to remove the given item or pop() method to remove an item at the given index. • The pop() method removes and returns the last item if index is not provided. • This helps us implement lists as stacks (first in, last out data structure). • We can also use the clear() method to empty a list. Raghavendra R Assistant Professor School of CS & IT 24 delete or remove elements from a list Unit 2 Lists, Tuples, Files
  • 25. my_list = ['p','r','o','b','l','e','m'] my_list.remove('p') # Output: ['r', 'o', 'b', 'l', 'e', 'm'] print(my_list) # Output: 'o' print(my_list.pop(1)) # Output: ['r', 'b', 'l', 'e', 'm'] print(my_list) # Output: 'm' print(my_list.pop()) # Output: ['r', 'b', 'l', 'e'] print(my_list) my_list.clear() # Output: [] print(my_list) Raghavendra R Assistant Professor School of CS & IT 25 delete or remove elements from a list Unit 2 Lists, Tuples, Files
  • 26. • Finally, we can also delete items in a list by assigning an empty list to a slice of elements. >>> my_list =['p','r','o','b','l','e','m'] >>> my_list[2:3] = [] >>> my_list ['p', 'r', 'b', 'l', 'e', 'm'] >>> my_list[2:5] = [] >>> my_list ['p', 'r', 'm'] Raghavendra R Assistant Professor School of CS & IT 26 delete or remove elements from a list Unit 2 Lists, Tuples, Files
  • 27. • List comprehension is an elegant and concise way to create a 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)] # 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) Raghavendra R Assistant Professor School of CS & IT 27 create new List Unit 2 Lists, Tuples, Files
  • 28. • A list comprehension can optionally contain more for or if statements. • An optional if statement 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'] Raghavendra R Assistant Professor School of CS & IT 28 Unit 2 Lists, Tuples, Files
  • 29. • The insert() method inserts an element to the list at a given index. • The syntax of insert() method is • list.insert(index, element) • The insert() function takes two parameters: • index - position where an element needs to be inserted • element - this is the element to be inserted in the list # vowel list vowel = ['a', 'e', 'i', 'u'] # inserting element to list at 4th position vowel.insert(3, 'o') print('Updated List: ', vowel) When you run the program, the output will be: Updated List: ['a', 'e', 'i', 'o', 'u'] Raghavendra R Assistant Professor School of CS & IT 29 List insert() Unit 2 Lists, Tuples, Files
  • 30. • The remove() method removes the first matching element (which is passed as an argument) from the list. • The syntax of the remove() method is: list.remove(element) remove() Parameters • The remove() method takes a single element as an argument and removes it from the list. • If the element doesn't exist, it throws ValueError: list.remove(x): x not in list exception. Raghavendra R Assistant Professor School of CS & IT 30 List remove() Unit 2 Lists, Tuples, Files
  • 31. # animals list animals = ['cat', 'dog', 'rabbit', 'guinea pig'] # 'rabbit' is removed animals.remove('rabbit') # Updated animals List print('Updated animals list: ', animals) Output Updated animals list: ['cat', 'dog', 'guinea pig'] Raghavendra R Assistant Professor School of CS & IT 31 Remove element from the list Unit 2 Lists, Tuples, Files
  • 32. # animals list animals = ['cat', 'dog', 'dog', 'rabbit', 'guinea pig‘, 'dog'] # ‘dog' is removed animals.remove(‘dog') # Updated animals List print('Updated animals list: ', animals) Output Updated animals list: ['cat', 'dog', 'guinea pig‘, ‘dog’] Here, only the first occurrence of element 'dog' is removed from the list. Raghavendra R Assistant Professor School of CS & IT 32 remove() method on a list having duplicate elements Unit 2 Lists, Tuples, Files
  • 33. • The index() method searches an element in the list and returns its index. • In simple terms, the index() method finds the given element in a list and returns its position. • If the same element is present more than once, the method returns the index of the first occurrence of the element. • Note: Index in Python starts from 0, not 1. • The syntax of the index() method is: list.index(element) Raghavendra R Assistant Professor School of CS & IT 33 List index() Unit 2 Lists, Tuples, Files
  • 34. # vowels list vowels = ['a', 'e', 'i', 'o', 'i', 'u'] # index of 'e' index = vowels.index('e') print('The index of e:', index) # index of the first 'i' index = vowels.index('i') print('The index of i:', index) Output The index of e: 1 The index of i: 2 Raghavendra R Assistant Professor School of CS & IT 34 Find the position of an element in the list Unit 2 Lists, Tuples, Files
  • 35. # random list random = ['a', ('a', 'b'), [3, 4]] # index of ('a', 'b') index = random.index(('a', 'b')) print("The index of ('a', 'b'):", index) # index of [3, 4] index = random.index([3, 4]) print("The index of [3, 4]:", index) Output The index of ('a', 'b'): 1 The index of [3, 4]: 2 Raghavendra R Assistant Professor School of CS & IT 35 Find the index of tuple and list inside a list Unit 2 Lists, Tuples, Files
  • 36. • The count() method returns the number of occurrences of an element in a list. • In simple terms, count() method counts how many times an element has occurred in a list and returns it. • The syntax of count() method is: list.count(element) Raghavendra R Assistant Professor School of CS & IT 36 List count() Unit 2 Lists, Tuples, Files
  • 37. # vowels list vowels = ['a', 'e', 'i', 'o', 'i', 'u'] # count element 'i' count = vowels.count('i') # print count print('The count of i is:', count) # count element 'p' count = vowels.count('p') # print count print('The count of p is:', count) When you run the program, the output will be: The count of i is: 2 The count of p is: 0 Raghavendra R Assistant Professor School of CS & IT 37 Count the occurrence of an element in the list Unit 2 Lists, Tuples, Files
  • 38. # random list random = ['a', ('a', 'b'), ('a', 'b'), [3, 4]] # count element ('a', 'b') count = random.count(('a', 'b')) # print count print("The count of ('a', 'b') is:", count) # count element [3, 4] count = random.count([3, 4]) # print count print("The count of [3, 4] is:", count) When you run the program, the output will be: The count of ('a', 'b') is: 2 The count of [3, 4] is: 1 Raghavendra R Assistant Professor School of CS & IT 38 Count the occurrence of tuple and list inside the list Unit 2 Lists, Tuples, Files
  • 39. • The pop() method removes the item at the given index from the list and returns the removed item. • The syntax of the pop() method is: list.pop(index) pop() parameters • The pop() method takes a single argument (index). • The argument passed to the method is optional. If not passed, the default index -1 is passed as an argument (index of the last item). • If the index passed to the method is not in range, it throws IndexError: pop index out of range exception. Raghavendra R Assistant Professor School of CS & IT 39 List pop() Unit 2 Lists, Tuples, Files
  • 40. # programming languages list languages = ['Python', 'Java', 'C++', 'French', 'C'] # remove and return the 4th item return_value = languages.pop(3) print('Return Value:', return_value) # Updated List print('Updated List:', languages) Output Return Value: French Updated List: ['Python', 'Java', 'C++', 'C'] Raghavendra R Assistant Professor School of CS & IT 40 Pop item at the given index from the list Unit 2 Lists, Tuples, Files
  • 41. # programming languages list languages = ['Python', 'Java', 'C++', 'Ruby', 'C'] # remove and return the last item print('When index is not passed:') print('Return Value:', languages.pop()) print('Updated List:', languages) # remove and return the last item print('nWhen -1 is passed:') print('Return Value:', languages.pop(- 1)) print('Updated List:', languages) # remove and return the third last item print('nWhen -3 is passed:') print('Return Value:', languages.pop(- 3)) print('Updated List:', languages) Output When index is not passed: Return Value: C Updated List: ['Python', 'Java', 'C++', 'Ruby'] When -1 is passed: Return Value: Ruby Updated List: ['Python', 'Java', 'C++'] When -3 is passed: Return Value: Python Updated List: ['Java', 'C++'] Raghavendra R Assistant Professor School of CS & IT 41 pop() without an index, and for negative indices Unit 2 Lists, Tuples, Files
  • 42. The reverse() method reverses the elements of a given list. The syntax of reverse() method is: list.reverse() reverse() parameter The reverse() function doesn't take any argument. Raghavendra R Assistant Professor School of CS & IT 42 List reverse() Unit 2 Lists, Tuples, Files
  • 43. # Operating System List os = ['Windows', 'macOS', 'Linux'] print('Original List:', os) # List Reverse os.reverse() # updated list print('Updated List:', os) When you run the program, the output will be: Original List: ['Windows', 'macOS', 'Linux'] Updated List: ['Linux', 'macOS', 'Windows'] Raghavendra R Assistant Professor School of CS & IT 43 Reverse a List Unit 2 Lists, Tuples, Files
  • 44. # Operating System List os = ['Windows', 'macOS', 'Linux'] # Printing Elements in Reversed Order for o in reversed(os): print(o) When you run the program, the output will be: Linux macOS Windows Raghavendra R Assistant Professor School of CS & IT 44 Accessing Individual Elements in Reversed Order Unit 2 Lists, Tuples, Files
  • 45. • The sort() method sorts the elements of a given list. • The sort() method sorts the elements of a given list in a specific order - Ascending or Descending. • The syntax of sort() method is: list.sort(key=..., reverse=...) • Alternatively, you can also use Python's in-built function sorted() for the same purpose. sorted(list, key=..., reverse=...) • Note: Simplest difference between sort() and sorted() is: sort() doesn't return any value while, sorted() returns an iterable list. Raghavendra R Assistant Professor School of CS & IT 45 List sort() Unit 2 Lists, Tuples, Files
  • 46. # vowels list vowels = ['e', 'a', 'u', 'o', 'i'] # sort the vowels vowels.sort() # print vowels print('Sorted list:', vowels) When you run the program, the output will be: Sorted list: ['a', 'e', 'i', 'o', 'u'] Raghavendra R Assistant Professor School of CS & IT 46 Sort a given list Unit 2 Lists, Tuples, Files
  • 47. # vowels list vowels = ['e', 'a', 'u', 'o', 'i'] # sort the vowels vowels.sort(reverse=True) # print vowels print('Sorted list (in Descending):', vowels) When you run the program, the output will be: Sorted list (in Descending): ['u', 'o', 'i', 'e', 'a'] Raghavendra R Assistant Professor School of CS & IT 47 Sort the list in Descending order Unit 2 Lists, Tuples, Files
  • 48. • Lists are ordered. • Lists can contain any arbitrary objects. • List elements can be accessed by index. • Lists can be nested to arbitrary depth. • Lists are mutable. • Lists are dynamic. Raghavendra R Assistant Professor School of CS & IT 48 Features of List Unit 2 Lists, Tuples, Files
  • 49. • A list is not merely a collection of objects. It is an ordered collection of objects. • The order in which you specify the elements when you define a list is an innate characteristic of that list and is maintained for that list’s lifetime. • Lists that have the same elements in a different order are not the same: >>> a = ['foo', 'bar', 'baz', 'qux'] >>> b = ['baz', 'qux', 'bar', 'foo'] >>> a == b False >>> a is b False >>> [1, 2, 3, 4] == [4, 1, 3, 2] False Raghavendra R Assistant Professor School of CS & IT 49 Lists are ordered. Unit 2 Lists, Tuples, Files
  • 50. • A list can contain any assortment of objects. The elements of a list can all be the same type: • >>> a = [2, 4, 6, 8] • >>> a [2, 4, 6, 8] Or the elements can be of varying types: • >>> a = [21.42, 'foobar', 3, 4, 'bark', False, 3.14159] • >>> a [21.42, 'foobar', 3, 4, 'bark', False, 3.14159] Raghavendra R Assistant Professor School of CS & IT 50 Lists can contain any arbitrary objects. Unit 2 Lists, Tuples, Files
  • 51. Lists can even contain complex objects, like functions, classes, and modules, which you will learn. >>> int <class 'int'> >>> len <built-in function len> >>> def foo(): ... pass ... >>> foo <function foo at 0x035B9030> >>> import math >>> math <module 'math' (built-in)> >>> a = [int, len, foo, math] >>> a [<class 'int'>, <built-in function len>, <function foo at 0x02CA2618>, <module 'math' (built-in)>] Raghavendra R Assistant Professor School of CS & IT 51 Unit 2 Lists, Tuples, Files
  • 52. A list can contain any number of objects, from zero to as many as your computer’s memory will allow: >>> a = [] >>> a [] >>> a = [ 'foo' ] >>> a ['foo'] >>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ... 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, ... 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, ... 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, ... 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100] Raghavendra R Assistant Professor School of CS & IT 52 Lists can be nested to arbitrary depth Unit 2 Lists, Tuples, Files
  • 53. • Individual elements in a list can be accessed using an index in square brackets. • This is exactly analogous to accessing individual characters in a string. • List indexing is zero-based as it is with strings. Consider the following list: >>> >>> a = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge'] The indices for the elements in a are shown below: Raghavendra R Assistant Professor School of CS & IT 53 List elements can be accessed by index Unit 2 Lists, Tuples, Files
  • 54. • The list is the first mutable data type you have encountered. • Once a list has been created, elements can be added, deleted, shifted, and moved around at will. • Python provides a wide range of ways to modify lists. A single value in a list can be replaced by indexing and simple assignment: >>> >>> a = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge'] >>> a ['foo', 'bar', 'baz', 'qux', 'quux', 'corge'] >>> a[2] = 10 >>> a[-1] = 20 >>> a ['foo', 'bar', 10, 'qux', 'quux', 20] Raghavendra R Assistant Professor School of CS & IT 54 Lists are mutable Unit 2 Lists, Tuples, Files
  • 55. Modifying Multiple List Values >>> a = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge'] >>> a[1:4] ['bar', 'baz', 'qux'] >>> a[1:4] = [1.1, 2.2, 3.3, 4.4, 5.5] >>> a ['foo', 1.1, 2.2, 3.3, 4.4, 5.5, 'quux', 'corge'] >>> a[1:6] [1.1, 2.2, 3.3, 4.4, 5.5] >>> a[1:6] = ['Bark!'] >>> a ['foo', 'Bark!', 'quux', 'corge'] The number of elements inserted need not be equal to the number replaced. Python just grows or shrinks the list as needed. Raghavendra R Assistant Professor School of CS & IT 55 Unit 2 Lists, Tuples, Files
  • 56. >>> a = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge'] >>> a[2:2] = [1, 2, 3] >>> a += [3.14159] >>> a ['foo', 'bar', 1, 2, 3, 'baz', 'qux', 'quux', 'corge', 3.14159] Similarly, a list shrinks to accommodate the removal of items: >>> a = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge'] >>> a[2:3] = [] >>> del a[0] >>> a ['bar', 'qux', 'quux', 'corge'] Raghavendra R Assistant Professor School of CS & IT 56 Lists are dynamic Unit 2 Lists, Tuples, Files
  • 57. • 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. 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.). Raghavendra R Assistant Professor School of CS & IT 57 Tuples Unit 2 Lists, Tuples, Files
  • 58. # Empty tuple my_tuple = () print(my_tuple) # Tuple having integers my_tuple = (1, 2, 3) print(my_tuple) # tuple with mixed datatypes my_tuple = (1, "Hello", 3.4) print(my_tuple) # nested tuple my_tuple = ("mouse", [8, 4, 6], (1, 2, 3)) print(my_tuple) Raghavendra R Assistant Professor School of CS & IT 58 Tuples Unit 2 Lists, Tuples, Files
  • 59. Create a Python Tuple With one Element • In Python, 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 a tuple, • var1 = ("Hello") # string • var2 = ("Hello",) # tuple • We can use the type() function to know which class a variable or a value belongs to. Raghavendra R Assistant Professor School of CS & IT 59 Tuples Unit 2 Lists, Tuples, Files
  • 60. • Access Python Tuple Elements • Like a list, each element of a tuple is represented by index numbers (0, 1, ...) where the first element is at index 0. • We use the index number to access tuple elements. For example, 1. Indexing • We can use the index operator [] to access an item in a tuple, where the index starts from 0. # accessing tuple elements using indexing letters = ("p", "r", "o", "g", "r", "a", "m", "i", "z") print(letters[0]) # prints "p" print(letters[5]) # prints "a" Raghavendra R Assistant Professor School of CS & IT 60 Tuples Unit 2 Lists, Tuples, Files
  • 61. 2. Negative Indexing • Python allows negative indexing for its sequences. • The index of -1 refers to the last item, -2 to the second last item and so on. For example, # accessing tuple elements using negative indexing letters = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z') print(letters[-1]) # prints 'z' print(letters[-3]) # prints 'r' Raghavendra R Assistant Professor School of CS & IT 61 Tuples Unit 2 Lists, Tuples, Files
  • 62. 3. Slicing • We can access a range of items in a tuple by using the slicing operator colon :. # accessing tuple elements using slicing my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z') # elements 2nd to 4th index print(my_tuple[1:4]) # prints ('r', 'o', 'g') # elements beginning to 2nd print(my_tuple[:-7]) # prints ('p', 'r') # elements 8th to end print(my_tuple[7:]) # prints ('i', 'z') # elements beginning to end print(my_tuple[:]) # Prints ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z') Raghavendra R Assistant Professor School of CS & IT 62 Tuples Unit 2 Lists, Tuples, Files
  • 63. • In Python ,methods that add items or remove items are not available with tuple. • Only the following two methods are available. • Some examples of Python tuple methods: my_tuple = ('a', 'p', 'p', 'l', 'e',) print(my_tuple.count('p')) # prints 2 print(my_tuple.index('l')) # prints 3 • Here, • my_tuple.count('p') - counts total number of 'p' in my_tuple • my_tuple.index('l') - returns the first occurrence of 'l' in my_tuple Raghavendra R Assistant Professor School of CS & IT 63 Tuples Methods Unit 2 Lists, Tuples, Files
  • 64. Iterating through a Tuple We can use the for loop to iterate over the elements of a tuple. For example, languages = ('Python', 'Swift', 'C++') # iterating through the tuple for language in languages: print(language) Raghavendra R Assistant Professor School of CS & IT 64 Tuples Unit 2 Lists, Tuples, Files
  • 65. Check if an Item Exists in the Tuple • We use the in keyword to check if an item exists in the tuple or not. For example, languages = ('Python', 'Swift', 'C++') print('C' in languages) # False print('Python' in languages) # True • Here, • 'C' is not present in languages, 'C' in languages evaluates to False. • 'Python' is present in languages, 'Python' in languages evaluates to True. Raghavendra R Assistant Professor School of CS & IT 65 Tuples Unit 2 Lists, Tuples, Files
  • 66. Raghavendra R Assistant Professor School of CS & IT 66 Tuples Unit 2 Lists, Tuples, Files
  • 67. • A set is an unordered collection of items. • Every element is unique (no duplicates) and must be immutable (which cannot be changed). • Sets can be used to perform mathematical set operations like union, intersection, symmetric difference etc. create a set • A set is created by placing all the items (elements) inside curly braces {}, separated by comma or by using the built-in function set(). • It can have any number of items and they may be of different types (integer, float, tuple, string etc.). • But a set cannot have a mutable element, like list, set or dictionary, as its element. Raghavendra R Assistant Professor School of CS & IT 67 Sets Unit 2 Lists, Tuples, Files
  • 68. # set do not have duplicates # Output: {1, 2, 3, 4} my_set = {1,2,3,4,3,2} print(my_set) # set cannot have mutable items # here [3, 4] is a mutable list # If you uncomment line #12, # this will cause an error. # TypeError: unhashable type: 'list' #my_set = {1, 2, [3, 4]} # we can make set from a list # Output: {1, 2, 3} my_set = set([1,2,3,2]) print(my_set) Raghavendra R Assistant Professor School of CS & IT 68 Unit 2 Lists, Tuples, Files
  • 69. Creating an empty set is a bit tricky. Empty curly braces {} will make an empty dictionary in Python. To make a set without any elements we use the set() function without any argument. # initialize a with {} a = {} # check data type of a # Output: <class 'dict'> print(type(a)) # initialize a with set() a = set() # check data type of a # Output: <class 'set'> print(type(a)) Raghavendra R Assistant Professor School of CS & IT 69 empty set Unit 2 Lists, Tuples, Files
  • 70. • Sets are mutable. But since they are unordered, indexing have no meaning. • We cannot access or change an element of set using indexing or slicing. Set does not support it. • We can add single element using the add() method and multiple elements using the update() method. • The update() method can take tuples, lists, strings or other sets as its argument. In all cases, duplicates are avoided. Raghavendra R Assistant Professor School of CS & IT 70 change a set Unit 2 Lists, Tuples, Files
  • 71. # initialize my_set my_set = {1,3} print(my_set) # add an element # Output: {1, 2, 3} my_set.add(2) print(my_set) # add multiple elements # Output: {1, 2, 3, 4} my_set.update([2,3,4]) print(my_set) # add list and set # Output: {1, 2, 3, 4, 5, 6, 8} my_set.update([4,5], {1,6,8}) print(my_set) Raghavendra R Assistant Professor School of CS & IT 71 Unit 2 Lists, Tuples, Files
  • 72. • A particular item can be removed from set using methods, discard() and remove(). • The only difference between the two is that, while using discard() if the item does not exist in the set, it remains unchanged. • But remove() will raise an error in such condition. Raghavendra R Assistant Professor School of CS & IT 72 remove elements Unit 2 Lists, Tuples, Files
  • 73. # initialize my_set my_set = {1, 3, 4, 5, 6} print(my_set) # discard an element # Output: {1, 3, 5, 6} my_set.discard(4) print(my_set) # remove an element # Output: {1, 3, 5} my_set.remove(6) print(my_set) # discard an element # not present in my_set # Output: {1, 3, 5} my_set.discard(2) print(my_set) # remove an element # not present in my_set # If you uncomment line 27, # you will get an error. # Output: KeyError: 2 #my_set.remove(2) Raghavendra R Assistant Professor School of CS & IT 73 Unit 2 Lists, Tuples, Files
  • 74. • 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. • A = {1, 2, 3, 4, 5} • B = {4, 5, 6, 7, 8} Raghavendra R Assistant Professor School of CS & IT 74 Set Operations Unit 2 Lists, Tuples, Files
  • 75. Set Union Union of A and B is a set of all elements from both sets. Union is performed using | operator. Same can be accomplished using the method union(). # initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # use | operator # Output: {1, 2, 3, 4, 5, 6, 7, 8} print(A | B) Raghavendra R Assistant Professor School of CS & IT 75 Unit 2 Lists, Tuples, Files
  • 76. Set Intersection • Intersection of A and B is a set of elements that are common in both sets. • Intersection is performed using & operator. • Same can be accomplished using the method intersection(). # initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # use & operator # Output: {4, 5} print(A & B) Raghavendra R Assistant Professor School of CS & IT 76 Unit 2 Lists, Tuples, Files
  • 77. 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().. # initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # use - operator on A # Output: {1, 2, 3} print(A - B) Raghavendra R Assistant Professor School of CS & IT 77 Unit 2 Lists, Tuples, Files
  • 78. Set Symmetric Difference • Symmetric Difference of A and B is a set of elements in both A and B except those that are common in both. • Symmetric difference is performed using ^ operator. • Same can be accomplished using the method symmetric_difference(). # initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # use ^ operator # Output: {1, 2, 3, 6, 7, 8} print(A ^ B) Raghavendra R Assistant Professor School of CS & IT 78 Unit 2 Lists, Tuples, Files
  • 79. Raghavendra R Assistant Professor School of CS & IT 79 Set Methods Unit 2 Lists, Tuples, Files
  • 80. • We can test if an item exists in a set or not, using the keyword in. # initialize my_set my_set = set("apple") # check if 'a' is present # Output: True print('a' in my_set) # check if 'p' is present # Output: False print('p' not in my_set) Raghavendra R Assistant Professor School of CS & IT 80 Set Membership Unit 2 Lists, Tuples, Files
  • 81. • Using a for loop, we can iterate though each item in a set. >>> for letter in set("apple"): ... print(letter) ... a p e l Raghavendra R Assistant Professor School of CS & IT 81 Iterating Through a Set Unit 2 Lists, Tuples, Files
  • 82. Function Description all() Return True if all elements of the set are true (or if the set is empty). any() Return True if any element of the set is true. If the set is empty, return False. enumerate() Return an enumerate object. It contains the index and value of all the items of set as a pair. len() Return the length (the number of items) in the set. max() Return the largest item in the set. min() Return the smallest item in the set. sorted() Return a new sorted list from elements in the set(does not sort the set itself). sum() Return the sum of all elements in the set. Raghavendra R Assistant Professor School of CS & IT 82 Built-in Functions with Set Unit 2 Lists, Tuples, Files
  • 83. • A file object allows us to use, access and manipulate all the user accessible files. • One can read and write any such files. • When a file operation fails for an I/O-related reason, the exception IOError is raised. • The first thing you’ll need to do is use Python’s built- in open function to get a file object. • The open function opens a file. • When you use the open function, it returns something called a file object. • File objects contain methods and attributes that can be used to collect information about the file you opened. • They can also be used to manipulate said file. Raghavendra R Assistant Professor School of CS & IT 83 File Objects Unit 2 Lists, Tuples, Files
  • 84. • Python has in-built functions to create and manipulate files. • The io module is the default module for accessing files and you don't need to import it. • The module consists of open(filename, access_mode) that returns a file object, which is called "handle". • You can use this handle to read from or write to a file. • Python treats the file as an object, which has its own attributes and methods. file_object = open(“filename”, “mode”) • where file_object is the variable to add the file object. • mode – tells the interpreter and developer which way the file will be used. Raghavendra R Assistant Professor School of CS & IT 84 Unit 2 Lists, Tuples, Files
  • 85. `open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)` • file is an argument that you have to provide to the open function. All other arguments are optional and have default values. Now, this argument is basically the path where your file resides. • If the path is in current working directory, you can just provide the filename, just like in the following examples: my_file_handle=open("mynewtextfile.txt") • If the file resides in a directory other than that, you have to provide the full path with the file name: my_file_handle=open("D:new_diranotherfile.txt") my_file_handle.read() Raghavendra R Assistant Professor School of CS & IT 85 Unit 2 Lists, Tuples, Files
  • 86. Access Modes • Access modes define in which way you want to open a file, you want to open a file for read only, write only or for both. • It specifies from where you want to start reading or writing in the file. • You specify the access mode of a file through the mode argument. • You use 'r', the default mode, to read the file. • In other cases where you want to write or append, you use 'w' or 'a', respectively. Raghavendra R Assistant Professor School of CS & IT 86 Unit 2 Lists, Tuples, Files
  • 87. Character Function r Open file for reading only. Starts reading from beginning of file. This default mode. rb Open a file for reading only in binary format. Starts reading from beginning of file. r+ Open file for reading and writing. File pointer placed at beginning of the file. w Open file for writing only. File pointer placed at beginning of the file. Overwrites existing file and creates a new one if it does not exists. wb Same as w but opens in binary mode. w+ Same as w but also alows to read from file. wb+ Same as wb but also alows to read from file. a Open a file for appending. Starts writing at the end of file. Creates a new file if file does not exist. ab Same as a but in binary format. Creates a new file if file does not exist. a+ Same a a but also open for reading. ab+ Same a ab but also open for reading. Raghavendra R Assistant Professor School of CS & IT 87 Unit 2 Lists, Tuples, Files
  • 88. Python Method • Method is called by its name, but it is associated to an object (dependent). • A method is implicitly passed the object on which it is invoked. • It may or may not return any data. • A method can operate on the data (instance variables) that is contained by the corresponding class. Raghavendra R Assistant Professor School of CS & IT 88 Difference between Method and Function Unit 2 Lists, Tuples, Files
  • 89. # Python 3 User-Defined Method class ABC : def method_abc (self): print("I am in method_abc of ABC class. ") class_ref = ABC() # object of ABC class class_ref.method_abc() Raghavendra R Assistant Professor School of CS & IT 89 Unit 2 Lists, Tuples, Files
  • 90. Functions • Function is block of code that is also called by its name. (independent) • The function can have different parameters or may not have any at all. If any data (parameters) are passed, they are passed explicitly. • It may or may not return any data. • Function does not deal with Class and its instance concept. Raghavendra R Assistant Professor School of CS & IT 90 Unit 2 Lists, Tuples, Files
  • 91. def Subtract (a, b): return (a-b) print( Subtract(10, 12) ) # prints -2 print( Subtract(15, 6) ) # prints 9 ************************** s = sum([5, 15, 2]) print( s ) # prints 22 mx = max(15, 6) print( mx ) # prints 15 Raghavendra R Assistant Professor School of CS & IT 91 Unit 2 Lists, Tuples, Files
  • 92. Method Description close() Close an open file. It has no effect if the file is already closed. detach() Separate the underlying binary buffer from the TextIOBase and return it. fileno() Return an integer number (file descriptor) of the file. flush() Flush the write buffer of the file stream. isatty() Return True if the file stream is interactive. read(n) Read atmost n characters form the file. Reads till end of file if it is negative or None. readable() Returns True if the file stream can be read from. readline(n=-1) Read and return one line from the file. Reads in at most n bytes if specified. Raghavendra R Assistant Professor School of CS & IT 92 File Built-in Methods Unit 2 Lists, Tuples, Files
  • 93. Method Description readlines(n=-1) Read and return a list of lines from the file. Reads in at most n bytes/characters if specified. seek(offset,from=SE EK_SET) Change the file position to offset bytes, in reference to from (start, current, end). seekable() Returns True if the file stream supports random access. tell() Returns the current file location. truncate(size=None) Resize the file stream to size bytes. If size is not specified, resize to current location. writable() Returns True if the file stream can be written to. write(s) Write string s to the file and return the number of characters written. writelines(lines) Write a list of lines to the file. Raghavendra R Assistant Professor School of CS & IT 93 File Built-in Methods Unit 2 Lists, Tuples, Files
  • 94. closed: returns a boolean indicating the current state of the file object. It returns true if the file is closed and false when the file is open. encoding: The encoding that this file uses. When Unicode strings are written to a file, they will be converted to byte strings using this encoding. mode: The I/O mode for the file. If the file was created using the open() built-in function, this will be the value of the mode parameter. Raghavendra R Assistant Professor School of CS & IT 94 File Built-in Attributes Unit 2 Lists, Tuples, Files
  • 95. name: If the file object was created using open(), the name of the file. newlines: A file object that has been opened in universal newline mode have this attribute which reflects the newline convention used in the file. The value for this attribute are “r”, “n”, “rn”, None or a tuple containing all the newline types seen. softspace: It is a boolean that indicates whether a space character needs to be printed before another value when using the print statement Raghavendra R Assistant Professor School of CS & IT 95 File Built-in Attributes Unit 2 Lists, Tuples, Files
  • 96. • f = open(__file__, 'a+') • print(f.closed) • print(f.encoding) • print(f.mode) • print(f.newlines) • print(f.softspace) Raghavendra R Assistant Professor School of CS & IT 96 File Built-in Attributes Unit 2 Lists, Tuples, Files
  • 97. • There are many options to read python command line arguments. The three most common ones are: • Python sys.argv • Python getopt module • Python argparse module Raghavendra R Assistant Professor School of CS & IT 97 Command Line Arguments Unit 2 Lists, Tuples, Files
  • 98. • Python sys module stores the command line arguments into a list, we can access it using sys.argv. • This is very useful and simple way to read command line arguments as String. • Let’s look at a simple example to read and print command line arguments using python sys module. • Below image illustrates the output of a sample run of above program. Raghavendra R Assistant Professor School of CS & IT 98 sys.argv module Unit 2 Lists, Tuples, Files
  • 99. • Python getopt module is very similar in working as the C getopt() function for parsing command-line parameters. • Python getopt module is useful in parsing command line arguments where we want user to enter some options too. • Let’s look at a simple example to understand this. Raghavendra R Assistant Professor School of CS & IT 99 getopt module Unit 2 Lists, Tuples, Files
  • 100. Above example is very simple, but we can easily extend it to do various things. For example, if help option is passed then print some user friendly message and exit. Here getopt module will automatically parse the option value and map them. Below image shows a sample run. Raghavendra R Assistant Professor School of CS & IT 100 Unit 2 Lists, Tuples, Files
  • 101. • Python argparse module is the preferred way to parse command line arguments. • It provides a lot of option such as positional arguments, default value for arguments, help message, specifying data type of argument etc. • At the very simplest form, we can use it like below. Raghavendra R Assistant Professor School of CS & IT 101 argparse module Unit 2 Lists, Tuples, Files
  • 102. Below is the output from quick run of above script. Raghavendra R Assistant Professor School of CS & IT 102 Unit 2 Lists, Tuples, Files
  • 103. Recursing Through Directories • In some situations you may need to recurse through directory after directory. This could be for any number of reasons. • In this example let’s look at how we can walk through a directory and retrieve the names of all the files: # This will walk through EVERY file in your computer import os # You can change the "/" to a directory of your choice for file in os.walk("/"): print(file) Raghavendra R Assistant Professor School of CS & IT 103 File system Unit 2 Lists, Tuples, Files
  • 104. • Being able to discern whether something is a file or directory can come in handy. • Let’s look at how you can check whether something is either a file or directory in Python. • To do this we can use the os.path.isfile() function which returns False if it’s a directory or True if it is indeed a file. >>> import os >>> os.path.isfile("/") False >>> os.path.isfile("./main.py") True Raghavendra R Assistant Professor School of CS & IT 104 File system Unit 2 Lists, Tuples, Files
  • 105. Checking if a File or Directory Exists • If you wanted to check whether something exists on your current machine you can use the os.path.exists() function, passing in the file or directory you wish to check: >>> import os >>> os.path.exists("./main.py") True >>> os.path.exists("./dud.py") False Raghavendra R Assistant Professor School of CS & IT 105 File system Unit 2 Lists, Tuples, Files
  • 106. Creating Directories in Python • Say you not only wanted to traverse directories but also wished to create your own. Well fear not, this is very possible using the os.makedirs() function. if not os.path.exists('my_dir'): os.makedirs('my_dir') • This will first go ahead and check to see if the directory my_dir exists, if it doesn’t exist then it will go ahead and call the os.makedirs('my_dir') in order to create our new directory for us. • It should be noted that this could potentially cause issues. • If you were to create the directory after checking that the directory doesn’t exist somewhere else, before your call to os.makedirs('my_dir') executes, you could see an OSError thrown. Raghavendra R Assistant Professor School of CS & IT 106 File system Unit 2 Lists, Tuples, Files
  • 107. • For the most part however you should be ok using the method mentioned above. • If you want to be extra careful and catch any potential exceptions then you can wrap you call to os.makedirs('my_dir') in a try...except like so: if not os.path.exists('my_dir'): try: os.makedirs('my_dir') except OSError as e: if e.errno != errno.EEXIST: raise Raghavendra R Assistant Professor School of CS & IT 107 File system Unit 2 Lists, Tuples, Files
  • 108. • File handling is basically the management of the files on a file system. • Every operating system has its own way to store files. • Python File handling is useful to work with files in our programs. • We don’t have to worry about the underlying operating system and its file system rules and operations. Raghavendra R Assistant Professor School of CS & IT 108 File Handling Unit 2 Lists, Tuples, Files
  • 109. Raghavendra R Assistant Professor School of CS & IT 109 Unit 2 Lists, Tuples, Files
  • 110. 1 2 3 4 5 6 7 demo_file = open('Demo.txt', 'r') # This statement will print every line in the file for x in demo_file: print (x) # close the file, very important demo_file.close() Raghavendra R Assistant Professor School of CS & IT 110 Unit 2 Lists, Tuples, Files open() function The open() function is used to open a file in a particular mode. It basically creates a file object which can be used for further manipulations. Syntax: open(file_name, mode) Different modes for opening a file: •r: Read •w: Write •a: Append •r+: Read and Write Initially, we need to create a file and place it in the same directory as of the script. Demo.txt Welcome to the programming world! Execute_file.py Output: Welcome to the programming world! Here, the Execute_file.py script opens the Demo.txt file and prints the entire content line-by-line.
  • 111. read() function The read() function is used to read the contents of the file. To achieve the same, we need to open a file in the read mode. demo_file = open("Demo.txt", "r") print(demo_file.read()) demo_file.close() Output: Welcome to the programming world! Raghavendra R Assistant Professor School of CS & IT 111 Unit 2 Lists, Tuples, Files
  • 112. write() function The write() function is used to write to a file and make changes to it. demo_file = open('Demo.txt','w') demo_file.write("Hello Everyone!.n") demo_file.write("Engineering Discipline.") demo_file.close() Output: When we open the Demo.txt file, we can see the changes reflected here. Hello Everyone!. Engineering Discipline. Raghavendra R Assistant Professor School of CS & IT 112 Unit 2 Lists, Tuples, Files
  • 113. append() function demo_file = open('Demo.txt','a') demo_file.write("nStatement added to the end of the file..") demo_file.close() Output: Hello Everyone!. Engineering Discipline. Statement added to the end of the file.. Raghavendra R Assistant Professor School of CS & IT 113 Unit 2 Lists, Tuples, Files
  • 114. split() function The split() function is used to split lines within a file. It splits up as soon as it encounters space in the script. Demo.txt Hello Everyone!. Engineering Discipline. Statement added to the end of the file.. Execute_file.py Raghavendra R Assistant Professor School of CS & IT 114 Unit 2 Lists, Tuples, Files
  • 115. with open("Demo.txt", "r") as demo_file: demo_data = demo_file.readlines() for line in demo_data: result = line.split() print(result) Output: ['Hello', 'Everyone!.'] ['Engineering', 'Discipline.'] ['Statement', 'added', 'to', 'the', 'end', 'of', 'the', 'file..'] Raghavendra R Assistant Professor School of CS & IT 115 Unit 2 Lists, Tuples, Files
  • 116. close() function • The close() function is used to close a particular file post manipulations on it. • After writing to a file, if we do not call the close() method, all the data written to the file will not be saved in it. • It’s always a good idea to close the file after we are done with it to release the resources. Syntax: file-name.close() Raghavendra R Assistant Professor School of CS & IT 116 Unit 2 Lists, Tuples, Files
  • 117. rename() function • The os module provides the rename() method to change the name of the particular file. Syntax: os.rename(current_name,new_name) Raghavendra R Assistant Professor School of CS & IT 117 Unit 2 Lists, Tuples, Files
  • 118. remove() method • The os module provides the remove() method to delete the file given as input. import os os.remove('Demo.txt') Before executing the remove() method.. Raghavendra R Assistant Professor School of CS & IT 118 Unit 2 Lists, Tuples, Files Output: After executing the remove() method