Unit 1 Introduction
Unit 1 Introduction
Introduction to
Python
Ms. Ankita J Desai
Assistant Professor
Department of Computer
Engineering
Outline
! Historyof python
! Features
! Python Implementation
! Python development and versions
! Python development environments
! Lexical Structure
! Data types
! Variables
! Assignment Statement
! del statement
! Expression & operators
! Control flow statements
History
! Python is developed by the Python Labs of Zope
Corporation, which consists of half a dozen core
developers headed by Guido van Rossum, the
Python's inventor, architect, and Benevolent
Dictator For Life (BDFL).
! Python was first released in 1991
! A message from the creator
Features
! Python is a dynamic, high level, free open source and
interpreted programming language
! Features:
! Easy to code
! Free and open source
! Object-oriented programming language
! GUI programming support
! High level language
! Extensible feature
! Portable language
! Interpreted language
! Large standard library
! Dynamically typed language
Python Implementation
! Python has two production quality
implementation
! Classic Python (CPython)
! Java Python (Jython)
! One experimental implementation
! Python .Net
Python Implementation
! Classic Python (CPython)
! It is the fastest, most up-to-date, most solid and
complete implementation of Python.
! It has a compiler, interpreter, and set of built-in
and optional extension modules, coded in
standard C.
! CPython can be used on any platform where
the C compiler complies
! CPython applications are generally faster,
particularly they can make good use of suitable
extension modules,
Python Implementation
! Java Python (Jython)
! Jython is a Python implementation for any Java Virtual
Machine (JVM) compliant with Java 1.2 or better.
! To use Jython well, you need some familiarity with
fundamental Java classes.
! The documentation and examples for existing Java
classes are couched in Java terms, so you need to be
acquainted with Java
! You also need to use Java supporting tools for tasks
such as manipulating .jar files and signing applets.
! Jython can use any Java class as an extension module,
whether the class comes from a standard Java library,
a third-party library, or a library you develop yourself.
Python Implementation
! Jython and CPython are both good, faithful
implementations of Python, reasonably close in
terms of usability and performance.
! Thus, it is wise to become familiar with the
strengths and weaknesses of each, to be able to
choose optimally for each development task.
Python Implementation
! The experimental Python .NET is a Python
implementation for the Microsoft .NET platform,
with an architecture similar to Jython’s.
! It is targeting Microsoft Intermediate Language
(MSIL) rather than JVM bytecode.
Python development and versions
! Python 2.0, released in 2000,
! Introduced features like list comprehensions
and a garbage collection system with
reference counting.
! Python 3.0 released in 2008 and current version of
python is 3.8.3 (as of June-2020).
! The Python 2 language was officially discontinued
in 2020
! Some of the differences between the two
versions of Python are:
Python development and versions
Python 2 Python 3
print “Hello World!!” print (“Hello World!!” )
{key1:value1, key2:value2,...}
! Example:
{1:’abc’,2:’xyz’}
! Empty dictionary is denoted by { }.
! Keys are unique within a dictionary while values may
not be. The values of a dictionary can be of any
type, but the keys must be immutable.
! The function dict creates a new dictionary with no items.
Because dict is the name of a built-in function, you
should avoid using it as a variable name.
! Ex:
a = dict()
print(a)
Output:
{}
! a = {}
print(a)
! Ex:
a = dict()
print(dict)
Output:
<type 'dict'>
Adding & Accessing items
! To add items to the dictionary, you can use
square brackets:
Ex:
a=dict()
a[1] = ‘abc‘
print(a)
Output:
{1: 'abc'}
Ex:
a=dict()
a[‘a’] = ‘abc‘
a['b'] = 'pqr'
print(a)
print(a[‘b’])
Output:
Output:
NameError: name 'b' is not defined
Ex:
dict={1:'Name',2:'xyz',2:'abc'}
print(dict)
print(dict[1])
print(dict[2])
Output:
! Ex:
a = {'a':'abc','b':'pqr'}
print(a)
print(a['a’])
print(a[‘c’])
Output:
{'a': 'abc', 'b': 'pqr'}
abc
KeyError: 'c'
Updating dictionary
(1) By adding new items/modifying existing entry:
Ex:
a = {'a': 'abc', 'b': 'pqr'}
a[‘a’]=‘zxc’
a['c']=8
print(a)
Output:
{'a': 'zxc', 'b': 'pqr', 'c': 8}
(2) Removing dictionary:
Ex:
a={1:'abc', 2:'pqr'}
del a[1]
print(a)
del a[2]
print(a)
a[1]='abc'
print(a)
a.clear()
print(a)
del a
print(a)
Output:
{2: 'pqr'}
{}
{1: 'abc'}
{}
NameError: name 'a' is not defined
Built-in dictionary functions
1. cmp(dict1, dict2)
cmp() compares two dictionaries based
on key and values.
! Syntax:
cmp(dict1, dict2)
! This method returns 0 if both dictionaries
are equal, -1 if dict1 < dict2 and 1 if dict1 >
dic2.
Ex:
len(dict)
Ex:
dict = {'Name': 'Zara', 'Age': 7}
print("Length : “, len(dict))
dict1 = {}
print("Length : “, len(dict1))
Output:
Length : 2
Length : 0
3. str(dict)
Produces a printable string representation of a
dictionary.
! Syntax:
str(dict)
Ex:
dict = {'Name': 'Zara', 'Age': 7}
print("Equivalent String : “, str (dict))
print(dict)
Output:
Equivalent String : {'Age': 7, 'Name': 'Zara'}
{'Age': 7, 'Name': 'Zara'}
4. type(variable)
Returns the type of the passed variable. If passed
variable is dictionary, then it would return a
dictionary type.
! Syntax:
type(dict)
Ex:
dict = {'Name': 'Zara', 'Age': 7}
print("Variable Type : “, type (dict))
Output:
Variable Type : <class 'dict'>
Built-in dictionary methods
1. dict.clear()
Removes all elements of dictionary dict.
! Syntax:
dict.clear()
Ex:
dict = {'Name': 'Zara', 'Age': 7}
print("Start Len : “, len(dict))
dict.clear()
print("End Len : “, len(dict))
Output:
Start Len : 2
End Len : 0
2. dict.copy()
Returns a copy of dictionary dict
! Syntax:
dict.copy()
Ex:
dict1 = {'Name': 'Zara', 'Age': 7};
dict2 = dict1.copy()
print("New Dictionary : “, str(dict2))
Output:
New Dictionary : {'Age': 7, 'Name': 'Zara'}
3. dict.fromkeys()
Create a new dictionary with keys from seq and
values set to value.
! Syntax:
dict.fromkeys(seq[, value])
Output:
New Dictionary : {'name': None, 'age': None}
New Dictionary : {'name': 10, 'age': 10}
# vowels keys
keys = {'a', 'e', 'i', 'o', 'u' }
value = [1]
{'a': [1], 'u': [1], 'o': [1], 'e': [1], 'i': [1]}
{'a': [1, 2], 'u': [1, 2], 'o': [1, 2], 'e': [1, 2], 'i': [1,
2]}
4. dict.get(key, default=None)
Returns a value for the given key. If key is not
available then returns default value None.
! Syntax:
dict.get(key, default=None)
Output:
Value : 7
Value : Never
Value : None
{'Age': 7, 'Name': 'Zabra'}
5. dict.has_key(key)
Returns true if key is in dictionary dict, false
otherwise
! Syntax:
dict.has_key(key)
Ex:
dict = {'Name': 'Zara', 'Age': 7}
print(“Answer : “, dict.has_key('Age’))
print(" Answer : “, dict.has_key('Education’))
Output:
Answer : True
Answer : False
! Python 3: has_key does not exist.
dict1 = {'Name': 'Zara', 'Age': 7}
if 'Age' in dict1:
print(‘True’)
6. dict.items()
Returns a list of dict's (key, value) tuple pairs
! Syntax:
dict.items()
Ex:
dict = {'Name': 'Zara', 'Age': 7}
print(“Answer : “, list(dict.items()))
Output:
Answer : [('Name', 'Zara'), ('Age', 7)]
7. dict.keys()
Returns list of dictionary dict's keys
! Syntax:
dict.keys()
Ex:
dict = {'Name': 'Zara', 'Age': 7}
dict1 = {}
print(“Key : “, dict.keys())
print("Value : “, dict1.keys())
Output:
Key : ['Age', 'Name']
Value : []
8. dict.setdefault(key, default=None)
Similar to get(), but will set dict[key]=default if key is
not already in dict
! Syntax:
dict.setdefault(key, default=None)
Ex:
dict = {'Name': 'Zara', 'Age': 7}
print("Value : ", dict.setdefault('Age', None))
print("Value : “, dict.setdefault('Education', 'Never’))
print("Value : ", dict.setdefault('Gender’))
print(dict)
Output:
Value : 7
Value : Never
Value : None
{'Name': 'Zara', 'Age’: 7, 'Education’: 'Never’, 'Gender’:
None}
! Difference between get() and setdefault()
methods:
data = {}
x = data.get('key',10)
print(x) #Output:10
print(data) #Output: {}
data = {}
x = data.setdefault('key',10)
print(x) #Output:10
print(data) #Output: {'key': 10}
9. dict.update(dict2)
Adds dictionary dict2's key-values pairs to dict. This
function does not return anything.
! Syntax:
dict.update(dict2)
Ex:
dict = {'Name': 'Zara', 'Age': 7}
dict2 = {'Gender': 'female' }
dict.update(dict2)
print("Value : “, dict)
print(dict2)
Output:
Value : {'Name': 'Zara', 'Age': 7, 'Gender': 'female'}
{'Gender': 'female'}
10. dict.values()
Returns list of dictionary dict's values
! Syntax:
dict.values()
Ex:
dict = {'Name': 'Zara', 'Age': 7}
dict2 = {}
print("Value : “, dict.values())
print("Value : “, dict2.values())
Output:
Value : [7, 'Zara']
Value : []
Ex:
a = {1: 'abc', 2: 'pqr', 3: 'xyz'}
print(1 in a)
print(4 in a)
val = a.values()
print('pqr' in val)
Output:
True
False
True
11. pop(), popitem()
Age
Name
Zara
{'Age': 7}
7
{}
{'N': 'Zara', 'A': 7}
('A', 7)
{'N': 'Zara'}
Looping and dictionaries
Problem: You are given a string and you want to count how
many times each letter appears.
! The for loop traverses the string. Each time through the loop, if
the character c is not in the dictionary, we create a new item
with key c and the initial value 1 (since we have seen this
letter once). If c is already in the dictionary we increment d[c].
! Brontosaurus
! {‘B’:1, ‘r’:2,
! Ex:
word = 'brontosaurus'
d = dict()
for c in word:
if c not in d:
d[c] = 1
else:
d[c] = d[c] + 1
print(d)
! Output:
{'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 2, 't': 1}
! We can use get to write our loop more concisely.
Because the get method automatically handles the
case where a key is not in a dictionary, we can
reduce four lines down to one and eliminate the if
statement.
word = 'brontosaurus'
d = dict()
for c in word:
d[c] = d.get(c,0) + 1
print(d)
! If you use a dictionary as the sequence in a for
statement, it traverses the keys of the dictionary. This
loop prints each key and the corresponding value.
Ex:
counts = { 1:'abc',2:'pqr',3:'xyz'}
for key in counts:
print(key, counts[key])
Output:
1 abc
2 pqr
3 xyz
Problem:
Find all the entries in a dictionary with a value above
ten.
counts = { ‘abc' : 1 , ‘pqr' : 42, ‘xyz': 100}
for key in counts:
if counts[key] > 10 :
print(key, counts[key])
Output:
pqr 42
xyz 100
! Problem:
Output:
['chuck', 'annie', 'jan']
annie 42
chuck 1
jan 100
! With a given integral number n, write a
program to generate a dictionary that
contains (i, i*i). Suppose the following input
is supplied to the program:
8
Then, the output should be:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}
Solution:
n=int(input())
d=dict()
for i in range(1,n+1):
d[i]=i*i
print(d)
Iteration in Python
While statement
• A while loop statement in Python
programming language repeatedly executes a
target statement as long as a given condition is
true.
• Syntax:
while expression:
statement(s)
• Ex:
count = 0
while (count<5):
print('The Count is:', count)
count = count + 1
print('Good Bye!!!')
Output:
The Count is: 0
The Count is: 1
The Count is: 2
The Count is: 3
The Count is: 4
Good Bye!!!
Using else Statement with while loop
Ex:
count = 0
while (count<5):
print(count, 'is less than 5')
count = count + 1
else:
print(count, 'is not less than 5’)
Output:
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5
for loop
• It has the ability to iterate over the items of any
sequence, such as a list or a string.
• Ex:
# First Example
for letter in 'Python':
print('Current Letter is:', letter)
# Second Example
fruits = ['banana','apple','mango']
for fruit in fruits:
print('Current fruit is:', fruit)
• Output:
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Current fruit : banana
Current fruit : apple
Current fruit : mango
• Iterating by Sequence Index:
An alternative way of iterating through each item is by index
offset into the sequence itself.
Ex:
fruits = ['banana','apple','mango']
for index in range(len(fruits)):
print('Current fruit is:', fruits[index])
Output:
Current fruit is: banana
Current fruit is: apple
Current fruit is: mango
Counting and summing loops
• Counting loops:
• Ex:
count = 0
for iterval in [3,41,12,9,74,15]:
count = count + 1
print("Answer is: ",count)
• Output:
Answer is: 6
• Summing loops:
Ex:
count = 0
total = 0
for iterval in [3,41,12,9,74,15]:
count = count + 1
total = total + iterval
print("Answer is: ",count)
print("Total is: ",total)
Output:
Answer is: 6
Total is: 154
Nested loops
• Syntax:
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
Output:
>#
>Hello
Hello
>done
DONE!!
continue and pass
• The continue statement in Python returns the control to the
beginning of the while/for loop. The continue statement rejects all
the remaining statements in the current iteration of the loop and
moves the control back to the top of the loop.
• Output:
Current Letter is: P
Current Letter is: y
Current Letter is: t
Current Letter is: h
Current Letter is: o
Current Letter is: n
Lists in Python
! List can be written as a list of comma-
separated values (items) between square
brackets.
! A list is that items in a list need not be of the
same type.
! Ex:
Output:
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
Deleting List Elements
! Ex:
list1 = ['physics', 'chemistry', 1997, 2000]
print(list1)
del list1[2]
print("After deleting value at index 2 : ")
print(list1)
Output:
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 : ['physics',
'chemistry', 2000]
Basic List Operations
Indexing, Slicing, and Matrixes
! For lists, a single position returns a values, a slice
returns a list.
! Ex:
l=[1,2,5,10]
print(l[0])
print(l[1:2])
Output:
1
[2]
Nested Lists
! Ex:
nested = [[2,[37]],4,["hello"]]
Output:
Value available at index 2 : 1997
New value available at index 2 : 2001
! Ex:
nested = [[2,[37]],4,["hello"]]
nested[1]=7
print(nested)
nested[0][1][0]=19
print(nested)
Output:
[[2, [37]], 7, ['hello']]
[[2, [19]], 7, ['hello']]
Mutable vs. Immutable
! Values of type int, float, bool, str are
immutable.
! In immutable data types, updating one value
does not affect the copy. Assignment makes
a fresh copy of a value.
! Ex:
x=5
y=x
print(y) #5
x=7
print(y) #5
! For mutable values, assignment does not
make a fresh copy.
! List is mutable.
! Ex:
l1=[1,3,5,7]
l2=l1
l1[2]=4
print(l1[2])
print(l2[2])
! Output:
4
4
l2 = l1[:]
! Ex:
l1=[1,3,5,7]
l2=l1[:]
l1[2]=4
print(l1)
print(l2)
! Output:
[1, 3, 4, 7]
[1, 3, 5, 7]
Digression on equality
! Consider the following lists:
l1=[1,3,5,7]
l2=[1,3,5,7]
l3=l2
! l1 == l2 is True.
! l2 == l3 is True.
! l2 is l3 is True.
! l1 is l2 is False.
Concatenation
! Listscan be glued together using +.
! Note that + always produces a new list.
! Ex:
l1=[1,3,5,7]
l2=l1
l1=l1+[9]
print(l1) #[1, 3, 5, 7, 9]
print(l2) #[1, 3, 5, 7]
Built-in List Functions
! len(list)
Ex:
list1, list2 = [123, 'xyz', 'zara'], [456, 'abc']
print("First list length : ", len(list1))
print("Second list length : ", len(list2))
Output:
First list length : 3
Second list length : 2
! max(list)
Ex:
list1, list2 = [123, 'xyz', 'zara', 'abc'], [456,
700, 200]
print("Max value element : ", max(list1))
print("Max value element : ", max(list2))
Output:
TypeError
700
! min(list)
Ex:
list1, list2 = [123, 'xyz', 'zara', 'abc'], [456, 700,
200]
print("Max value element : ", max(list1))
print("Max value element : ", max(list2))
Output:
TypeError
200
! list(
seq )
Converts tuple into list.
Ex:
aTuple = (123, 'xyz', 'zara', 'abc')
aList = list(aTuple)
print("List elements : ", aList)
Output:
List elements : [123, 'xyz', 'zara', 'abc']
Methods
! list.append()
Ex:
aList = [123, 'xyz', 'zara', 'abc']
aList.append(2009);
print("Updated List : ", aList)
Output:
Updated List : [123, 'xyz', 'zara', 'abc',
2009]
! list.extend()
Ex:
aList = [123, 'xyz', 'zara', 'abc', 123]
bList = [2009, 'manni']
aList.extend(bList)
print("Extended List : ", aList)
Output:
Extended List : [123, 'xyz', 'zara', 'abc',
123, 2009, 'manni']
! Ex:
l1=[1,3,5,7]
l1.append(9)
print(l1)
#l1.extend(10) #not allowed
l1.extend([6,8])
l1.append([1,2])
print(l1)
! Output:
[1, 3, 5, 7, 9]
[1, 3, 5, 7, 9, 6, 8, [1, 2]]
! list.count()
Ex:
aList = [123, 'xyz', 'zara', 'abc', 123]
print("Count for 123 : ", aList.count(123))
print("Count for zara : ", aList.count('zara'))
Output:
Count for 123 : 2
Count for zara : 1
!list.copy()
Ex:
list1 = ['cat', 0, 6.7]
new_list = list1.copy()
#new_list = list1[:]
new_list.append('dog')
print('Old List: ', list1)
print('New List: ', new_list)
Output:
Old List: ['cat', 0, 6.7]
New List: ['cat', 0, 6.7, 'dog']
! list.index()
Ex:
aList = [123, 'xyz', 'zara', 'abc']
print("Index for xyz : ", aList.index( 'xyz' ))
print("Index for zara : ", aList.index( 'zara' ))
Output:
Index for xyz : 1
Index for zara : 2
! list.insert()
Ex:
aList = [123, 'xyz', 'zara', 'abc']
aList.insert( 3, 2009)
print("Final List : ", aList)
Output:
Final List : [123, 'xyz', 'zara', 2009, 'abc']
Output:
A List : abc
[123, 'xyz', 'zara']
B List : zara
[123, 'xyz']
! list.remove()
Ex:
aList = [123, 'xyz', 'zara', 'abc', 'xyz'];
aList.remove('xyz');
print("List : ", aList)
aList.remove('abc');
print("List : ", aList)
Output:
List : [123, 'zara', 'abc', 'xyz']
List : [123, 'zara', 'xyz']
! list.reverse()
Ex:
aList = [123, 'xyz', 'zara', 'abc', 'xyz'];
aList.reverse();
print("List : ", aList)
Output:
List : ['xyz', 'abc', 'zara', 'xyz', 123]
! list.sort()
Ex:
aList = ['xyz', 'zara', 'abc', 'xyz'];
aList.sort();
print("List : ", aList)
Output:
List : ['abc', 'xyz', 'xyz', 'zara']
#Try aList.sort(reverse=True)
! Ex:
l=[1,2,3,4]
l[1:4]=[6,7]
print(l)
l[1:1]=[8,9]
print(l)
l[1]=[8,9]
print(l)
Output:
[1, 6, 7]
[1, 8, 9, 6, 7]
[1, [8, 9], 9, 6, 7]
Problem:
! Define a function which can generate
and print a list where the values are square
of numbers between 1 and 20 (both
included).
def printList():
li=list()
for i in range(1,21):
li.append(i**2)
print(li)
printList()
Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169,
196, 225, 256, 289, 324, 361, 400]
! l=[['Hi'] * 4]
print(l)
! l=[[] * 4]
print(l)
! l=[['Hi' * 4]]
print(l)
! l=[['Hi']] * 4
print(l)
Predict output:
! l=[[]] * 4
print(l) #output: [[], [], [], []]
! l=[['Hi'] * 4]
print(l) #output: [['Hi', 'Hi', 'Hi', 'Hi']]
! l=[[] * 4]
print(l) #output: [[]]
! l=[['Hi' * 4]]
print(l) #output: [['HiHiHiHi']]
! l=[['Hi']] * 4
print(l) #output: [['Hi'], ['Hi'], ['Hi'], ['Hi']]
Problem:
Syntax:
[ expression for item in list if condition ]
List = []
For item in list:
If condition:
x = expression
List2 = list(x)
# You can either use loops:
squares = []
for x in range(10):
squares.append(x**2)
Print(squares)
Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
list1 = [3,4,5]
multiplied = [item*3 for item in list1]
Print(multiplied)
Output: [9,12,15]
Problem:
! Show the first letter of each word.
Problem:
! Use a list comprehension to square each
odd number in a list. The list is input by a
sequence of comma-separated numbers.
! Suppose the following input is supplied to
the program:
1,2,3,4,5,6,7,8,9
Then, the output should be:
1,3,5,7,9
values = input()
numbers = [x for x in values.split(",") if int(x)%2!
=0]
print(",".join(numbers))
Problem
! Print first letter of each word.
Problem
! Print first letter of each word.
listOfWords = ["this","is","a","list","of","words"]
items = [word[0] for word in listOfWords]
print(items)
Output:
[12, 24, 88]
Problem
! Writea program generate a 3*5*8 3D
array whose each element is 0.
!array = [0 for col in range(8)]
print(array)
#output: [0, 0, 0, 0, 0, 0, 0, 0]
s=set([1,2,3,4,1,2,1])
print(s)
Output:
{1, 2, 3, 4}
! A set can also be created by placing all the
items (elements) inside curly braces {}.
! 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.
! Ex:
s={1,2,3,4,"helllo",(1,2,3)}
print(s)
Output:
{1, 2, 3, 4, (1, 2, 3), 'helllo'}
! 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.
Iteration Over Sets
! Ex:
s=set([1,2,3,4,1,2,1]) #we can make set from list
for i in s:
print(i)
Output:
1
2
3
4
! Ex:
s=set()
s.add("Red")
print(s)
s.update(["Blue", "Green"])
print(s)
Output:
{'Red'}
{'Red', 'Blue', 'Green'}
! Ex:
s={1,2,3,4,"helllo",(1,2,3)}
s.update([4,5,6],{1,7,8})
print(s)
Output:
{1, 2, 3, 4, 5, 6, 7, 8, (1, 2, 3), 'helllo'}
Removing items from set
! Ex:
s=set([0,1,2,3,1,3,4,2])
print(s)
s.pop() #any item will be popped
print(s)
s.pop()
print(s)
s.remove(3)
print(s)
s.discard(4)
print(s)
Output:
{0, 1, 2, 3, 4}
{1, 2, 3, 4}
{2, 3, 4}
{2, 4}
{2}
Output:
{'blue'}
Union of sets
! Ex:
setx = set(["green", "blue"])
sety = set(["blue", "yellow"])
setz = setx | sety
print(setz)
#print(setx|sety))
#print(setx.union(sety))
Output:
{'green', 'blue', 'yellow'}
Set difference
! Ex:
setx = set(["green", "blue"])
sety = set(["blue", "yellow"])
setz = setx - sety
print(setz)
#print(setx - sety)
#print(setx.difference(sety))
Output:
{'green'}
issubset and issuperset
! Ex:
setx = set(["green", "blue"])
sety = set(["blue", "yellow", "green"])
sub = setx <= sety
print(sub)
sup = setx >= sety
print(sup)
Output:
True
False
! EX:
A={1,2,3,4}
B={3,4}
print(A.issubset(B))
print(A.issuperset(B))
print(A.isdisjoint(B))
Output:
False
True
False
Shallow copy of sets
! Ex:
Output:
{'blue', 'green'}
Set Membership Test
! We can test if an item exists in a set or not,
using the keyword in.
! Ex:
A = set("apple")
print('a' in A)
print('p' not in A)
Output:
True
False
Built-in Functions with Set
Frozenset
! Frozenset is has the characteristics of a set,
but its elements cannot be changed once
assigned.
! While tuples are immutable lists, frozensets
are immutable sets.
! Frozensets can be created using the
function frozenset().
! Ex:
A = frozenset("apple")
! This datatype supports methods like
copy(), difference(), intersection(),
isdisjoint(), issubset(), issuperset(),
symmetric_difference() and union(). Being
immutable it does not have method that
add or remove elements.
Tuple in
Python
!A tuple is a sequence of immutable
Python objects.
! Tuples are sequences, just like lists.
! The differences between tuples and lists
are, the tuples cannot be changed unlike
lists and tuples use parentheses, whereas
lists use square brackets.
Creating Tuple
Creating a tuple is as simple as putting
different comma-separated values.
! Ex:
t = (1)
print(t[0])
Ex:
t = (1,)
print(t[0])
Accessing Values in Tuples
! Toaccess values in tuple, use the square
brackets for slicing along with the index or
indices to obtain value available at that
index.
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )
print("tup1[0]: ", tup1[0])
print("tup2[1:5]: ", tup2[1:5])
Output:
tup1[0]: physics
tup2[1:5]: (2, 3, 4, 5)
! Nested tuples are accessed using nested
indexing.
! Ex:
t = ("mouse",[8,4,6],(1,2,3))
print(t[0])
print(t[0][3])
print(t[1][2])
Output:
mouse
s
6
Adding elements to tuple
! Ex:
t=()
for i in range(5):
t=t+(i,)
print(t)
Output:
(0, 1, 2, 3, 4)
Updating Tuple
! Tuples are immutable which means you
cannot update or change the values of
tuple elements once inserted.
tup1 = (12, 34.56)
tup2 = ('abc', 'xyz')
# Following action is not valid for tuples
# tup1[0] = 100
# So let's create a new tuple as follows
tup3 = tup1 + tup2
print(tup3)
Output:
(12, 34.56, 'abc', 'xyz')
! If the element is itself a mutable data type
like list, its nested items can be changed.
! Ex:
t = ("mouse",[8,4,6],(1,2,3))
t[1][1]=5
print(t)
Output:
('mouse', [8, 5, 6], (1, 2, 3))
Deleting Tuple Elements
! Removing individual tuple elements is not
possible.
! To explicitly remove an entire tuple, just
use the del statement.
! Ex:
tup = ('physics', 'chemistry', 1997, 2000)
print(tup)
del tup
print("After deleting tup : ")
print(tup)
Basic Tuples Operations
! Tuples respond to the + and * operators much
like strings; they mean concatenation and
repetition here too, except that the result is a
new tuple, not a string.
Indexing, Slicing
! Because tuples are sequences, indexing
and slicing work the same way for tuples
as they do for strings.
Output:
First tuple length : 3
Second tuple length : 2
max(tuple)
! Ex:
Output:
Max value element : zara
Max value element : 700
min(tuple)
! Ex:
Output:
Max value element : abc
Max value element : 200
tuple(seq)
! Ex:
Output:
Tuple elements : (123, 'xyz', 'zara', 'abc')
Methods
! count(x)
Ex:
t = (1,2,3,1,2,1,4)
print(t.count(1))
Output:
3
! index(x)
! Ex:
t = (1,2,3,1,2,1,4)
print(t.index(2))
Output:
1
Tuple Membership Test
! We can test if an item exists in a tuple or not,
using the keyword in.
! Ex:
t = (1,2,3,1,2,1,4)
print(1 in t)
print(2 not in t)
Output:
True
False
Iterating Through a Tuple
! Ex:
Output:
Hello abc
Hello xyz
Tuple with string functions
! Ex:
s=input()
t=tuple(s.split(“ "))
print(t)
Output:
I am student
(‘I', 'am', ‘student')
Advantages over lists
! Tuples that contain immutable elements
can be used as key/value pair for a
dictionary. With list, this is not possible.
! Ex: