0% found this document useful (0 votes)
2 views

Unit 1 Introduction

This document provides an introduction to Python, covering its history, features, implementations, development environments, lexical structure, data types, and dictionaries. It discusses the evolution of Python from version 2.0 to 3.0, highlighting key differences and the importance of understanding various implementations like CPython and Jython. Additionally, it explains the structure and usage of Python's data types, including numbers, strings, tuples, and dictionaries, along with examples of their operations.

Uploaded by

gorasiaharshil8
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Unit 1 Introduction

This document provides an introduction to Python, covering its history, features, implementations, development environments, lexical structure, data types, and dictionaries. It discusses the evolution of Python from version 2.0 to 3.0, highlighting key differences and the importance of understanding various implementations like CPython and Jython. Additionally, it explains the structure and usage of Python's data types, including numbers, strings, tuples, and dictionaries, along with examples of their operations.

Uploaded by

gorasiaharshil8
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 219

Unit -1:

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!!” )

raw_input (‘What is your name?’) Input (‘What is your name?’)


Python development environments
!A development environment is a combination of
a text editor and a Python runtime
implementation.
! The text editor allows you to write code for your
applications.
! The runtime implementation, such as CPython
or Jython, provides the method for executing
your code.
Lexical Structure
! The lexical structure of a programming language
is the set of basic rules that govern how you write
programs in that language.
! Each Python source file, like any other text file, is a
sequence of characters.
! Python is very particular about program layout,
especially with regard to lines and indentation
!
Lexical Structure
! Lines and Indentation
! A Python program is composed of a sequence of
logical lines, each made up of one or more physical
lines.
! Each physical line may end with a comment.
! A hash sign (#) that is not inside a string literal begins
a comment.
! All characters after the # and up to the physical line
end are part of the comment, and the Python
interpreter ignores them.
! In an interactive interpreter session, you must enter an
empty physical line (without any whitespace or
comment) to terminate a multiline statement.
Lexical Structure
! Linesand Indentation
! To show the continuity of lines, use back slash (\) at
the end of the physical line
! Python uses indentation to express the block structure
of a program.
! Each logical line in a Python program is indented by
the whitespace on its left.
! A block is a contiguous sequence of logical lines, all
indented by the same amount; a logical line with less
indentation ends the block.
! The first statement in a source file must have no
indentation (i.e., must not begin with any
whitespace).
Lexical Structure
! Character Set
! A Python source file must be entirely made up of characters
from the ASCII set (character codes between 0 and 127).
! But one can choose to tell Python that in a certain source file
you are using a character set that is a superset of ASCII.
! Python allows that specific source file to contain characters
outside the ASCII set, but only in comments and string literals.
! To accomplish this, start your source file with a comment as
follows:
! # -*- coding: utf-8 -*-
! Between the coding: and the -*-, mention the codec known
to Python, such as utf-8 or iso-8859-1.
! This coding directive comment is taken as such only if it is at
the start of a source file
Lexical Structure
! Tokens
! Python breaks each logical line into a
sequence of elementary lexical components
known as tokens.
! The normal token types are identifiers,
keywords, operators, delimiters, and literals.
Lexical Structure
! Tokens
! Identifiers
! An identifier is a name used to identify a variable, function,
class, module, or other object.
! An identifier starts with a letter (A to Z or a to z) or an underscore
(_) followed by zero or more letters, underscores, and digits (0 to
9).
! They are case sensitive.
! Python does not allow punctuation characters such as @, $, and
% within identifiers.
! Normal Python style is to start class names with an uppercase
letter and all other identifiers with a lowercase letter.
! Starting an identifier with a single leading underscore indicates
private identifier.
! Starting an identifier with two leading underscores indicates a
strongly private identifier
Lexical Structure
! Tokens
! Keywords
! Python has 30 keywords, which are identifiers
that Python reserves for special syntactic
uses.
! Keywords contain lowercase letters only.
! You cannot use keywords as regular
identifiers.
Lexical Structure
! Tokens
! Keywords
Lexical Structure
! Tokens
! Operators
! Pythonuses non-alphanumeric characters
and character combinations as operators.
Lexical Structure
! Tokens
! Delimiters
! Python uses the following symbols and symbol
combinations as delimiters in expressions, lists,
dictionaries, various aspects of statements,
and strings, among other purposes:
Lexical Structure
! Tokens
! Literals
!A literal is a number or string that appears
directly in a program. The following are all
literals in Python:
Data Types
! Alldata values in Python are represented by
objects, and each object, or value, has a type.
An object's type determines what operations the
object supports.
! The built-in type(obj) accepts any object as its
argument and returns the type object that
represents the type of obj.
! An object that can be altered is known as a
mutable object, while one that cannot be
altered is an immutable object.
! Examples
Data Type
! Numbers
! Allnumbers in Python are immutable objects
! Python support integers (plain and long),
floating-point numbers, and complex numbers.
! 1, 23, 3493 # Decimal integers
! 01, 027, 06645 # Octal integers
! 0x1, 0x17, 0xDA5 # Hexadecimal integers
Data Type
! Iterables
! iterable - an object that can be “iterated over”
! An iterable is any Python object capable of
returning its members one at a time, permitting
it to be iterated over in a for-loop.
! e.g., list, tuples, strings, dictionaries and sets
! Unpacking iterates
Data Type
! Iterables
! Enumerating Iterables
! The built-in enumerate function allows us to
iterate over an iterable, while keeping track
of the iteration count
!
Data Type
! Sequences
!A sequence is an ordered container of items,
indexed by non-negative integers. Python
provides built-in sequence types for strings
(plain and Unicode), tuples, and lists.
Data Type
! Strings
!A built-in string object is an ordered collection
of characters used to store and represent text-
based information.
! It is a mutable object
Data Type
! Tuples
!A tuple is a sequence of values
! The values stored in a tuple can be of any type,
and they are indexed by integers.
!
! Tuples
Dictionary
in Python
! Dictionary is one of the data type in python.
! It is mapping between key and values. The
association of a key and a value is called a key-
value pair or sometimes an item.
! Lists are ordered set of objects, whereas dictionaries
are unordered sets.
! Items in dictionaries are accessed via keys and not
via their position.
! Syntax of dictionary:

{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:

{'a': 'abc', 'b': 'pqr'}


pqr
Ex:
a=dict()
a[b] = 'abc‘
print(a)

Output:
NameError: name 'b' is not defined
Ex:
dict={1:'Name',2:'xyz',2:'abc'}
print(dict)
print(dict[1])
print(dict[2])

Output:

{1: 'Name', 2: 'abc'} N


ame
abc
! Attempting to access a data item with a key, which is not
part of dictionary will result in error.

! 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:

dict1 = {'Name': 'abc', 'Age': 7}


dict2 = {'Name': 'abc', 'Age': 7}
dict3 = {'Name': 'abc', 'Age': 27}
dict4 = {'Name': 'AAc', 'Age': 7}
dict5 = {'Name': 'ABc', 'Age': 7}
dict6 = {'Name': 'abc', 'Age': 31}
dict7 = {'Name': 'pqr'}
print "Return Value : %d" % cmp (dict1, dict2)
#print cmp(dict1, dict2)
print "Return Value : %d" % cmp (dict2, dict3)
print "Return Value : %d" % cmp (dict1, dict4)
print "Return Value : %d" % cmp (dict4, dict5)
print "Return Value : %d" % cmp (dict4, dict6)
print "Return Value : %d" % cmp (dict1, dict7)
Output:
Return Value : 0
Return Value : -1
Return Value : 1
Return Value : -1
Return Value : -1
Return Value : 1
! Python 3: cmp does not exist
Ex:
if dict1==dict2:
print(“True”)
2. len(dict)
Gives the total length of the dictionary. This would be
equal to the number of items in the dictionary.
! Syntax:

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])

seq -- This is the list of values which would be used for


dictionary keys preparation.
value -- This is optional, if provided then value would
be set to this value.
Ex:
seq = ('name', 'age')
dict = dict.fromkeys(seq)
print("New Dictionary : “, str(dict))
dict = dict.fromkeys(seq, 10)
print("New Dictionary : “, str(dict))

Output:
New Dictionary : {'name': None, 'age': None}
New Dictionary : {'name': 10, 'age': 10}
# vowels keys
keys = {'a', 'e', 'i', 'o', 'u' }
value = [1]

vowels = dict.fromkeys(keys, value)


print(vowels)

# updating the value


value.append(2)
print(vowels)
! Output:

{'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)

key -- This is the Key to be searched in the dictionary.


default -- This is the Value to be returned in case key
does not exist.
Ex:
dict = {'Name': 'Zabra', 'Age': 7}
print("Value : " , dict.get('Age’))
print("Value : “, dict.get('Education', ‘Never’))
print("Value : “, dict.get(‘Gender’,0))
print(dict)

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()

dict = {'Name': 'Zara', 'Age': 7}


print(min(dict))
print(max(dict))
print(dict.pop('Name'))
print(dict)
print(dict.pop('Age'))
print(dict)
dict['N']='Zara'
dict['A']=7
print(dict)
print(dict.popitem())
print(dict)
! Output:

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:

Print keys in alphabetical order.


d = {'chuck' : 1 , 'annie' : 42, 'jan': 1
00}
lst = list(d.keys())
print(lst)
l = sorted(lst)
for i in l:
print(i, d[i])

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)

• Syntax of nested while:


while expression:
while expression:
statement(s)
statement(s)
Continue and break
• Ex:
while True:
line = input('>')
if line[0] == '#':
continue
if line == 'done':
break
print(line)
print(“DONE!!")

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.

• The pass statement in Python is used when a statement is required


syntactically but you do not want any command or code to execute.
The pass statement is a null operation; nothing happens when it
executes.
• Ex:
for letter in 'Python':
if letter == 'h':
continue
print('Current Letter is:', letter)
• Output:
Current Letter is: P
Current Letter is: y
Current Letter is: t
Current Letter is: o
Current Letter is: n

for letter in 'Python':


if letter == 'h':
pass
print 'Current Letter :', letter
• Ex:
for letter in 'Python':
if letter == 'h':
pass
print('Current Letter is:', letter)

• 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:

list1 = ['physics', 'chemistry', 1997, 2000]


list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
Accessing Values in Lists
! Similar to string indices, list indices start at 0.
! Ex:
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7 ]
print("list1[0]: ", list1[0])
print("list2[1:5]: ", list2[1:5])

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"]]

print(nested[0]) # [2, [37]]


print(nested[1]) #4
print(nested[2]) # ['hello']
print(nested[0][0]) #2
print(nested[0][1]) #[37]
print(nested[0][1][0]) #37
print(nested[2][0]) #hello
print(nested[2][0][0]) #h
print(nested[0][1:2]) #[[37]]
Updating Lists
! Ex:
list = ['physics', 'chemistry', 1997, 2000]
print("Value available at index 2 : ", list[2])
list[2] = 2001
print("New value at index 2 : ", list[2])

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

! l1 and l2 are two names for the same list.

! What if we don’t want this?


! We can use slice, because it creates list
from old one.
! Recall that
l[:k] is l[0:k]
l[k:] is l[k:len(l)]

! Omitting both ends gives a full slice.


! To make copy of a list, use a full slice.

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

! All three lists are equal, but there is a


difference.
! l1 and l2 are lists with same value.
! l2 and l3 are two names for same list.
! x==y checks is x and y have same value.
! x is y checks if x and y refer to same object.

! 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']

#try aList.insert(5, [2009,2008])


!list.pop()
Ex:
aList = [123, 'xyz', 'zara', 'abc']
print("A List : ", aList.pop())
print(aList)
print("B List : ", aList.pop(2))
print(aList)

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]

#Try with print(li[:5]), print(li[-5:]), print(li[5:]),


print(li[1:5])
Problem:
! Write
a Python program to check a list is
empty or not.
l = []
if not l:
print("List is empty")
Predict output:
! l=[[]] * 4
print(l)

! 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:

Write a Python program to multiply all the


items in a list.
def multiply_list(items):
tot = 1
for x in items:
tot *= x
return tot
print(multiply_list([1,2,-8]))
Problem:

Write a Python program to concatenate


elements of a list.
color = ['red', 'green', 'orange']
print('-'.join(color))
print(''.join(color))
List Comprehension
x = [i for i in range(10)]
print(x )
# This will give the output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

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]

# Or you can use list comprehensions to get


the same result:
squares = [x**2 for x in range(10)]
Print(squares)
Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Problem:
! Multiply every part of a list by three and
assign it to a new list.
Problem:
! Multiply every part of a list by three and
assign it to a new list.

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: ['t', 'i', 'a', 'l', 'o', 'w']


Problem
! Write
a program to print the list after
removing even numbers in it.
li = [5,6,77,45,22,12,24]
li = [x for x in li if x%2!=0]
print(li)
Problem
! Write a program to print the list after
removing numbers which are divisible by 5
and 7.
Ex:
li = [12,24,35,70,88,120,155]
li = [x for x in li if x%5!=0 and x%7!=0]
print(li)

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]

!array = [[0 for col in range(8)]]


print(array)
#output: [[0, 0, 0, 0, 0, 0, 0, 0]]

!array = [[0 for col in range(8)] for i in range(5)]


print(array)
#output: [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0,
0, 0, 0, 0, 0]]
!array = [[ [0 for col in range(8)] for col in
range(5)] for row in range(3)]
print(array)
#output:
[[[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0,
0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0,
0, 0, 0, 0, 0]], [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0,
0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0,
0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], [[0, 0, 0, 0, 0, 0, 0,
0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]]
Problem
! write a program to print the list after
removing the value 24 in
[12,24,35,24,88,120,155].
li = [12,24,35,24,88,120,155]
li = [x for x in li if x!=24]
print(li)
Problem
! write a program using list comprehension
to print the Fibonacci Sequence.
! If the following n is given as input to the
program:
7
Then, the output of the program
should be:
[0,1,1,2,3,5,8,13]
def f(n):
if n == 0: return 0
elif n == 1: return 1
else: return f(n-1)+f(n-2)
n=int(input())
values = [f(x) for x in range(0, n+1)]
print(values)
Sets in Python
!A set object is an unordered collection of
objects.
! It is commonly used in membership testing,
removing duplicates from a sequence,
and computing mathematical operations
such as intersection, union, difference, and
symmetric difference.
! Ex:

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

We can apply dictionary as argument.


Adding members in set
! We can add single element using the add() method and
multiple elements using the update() method. The update()
method can take tuples, lists, strings, dictionary or other sets as
its argument.

! 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}

- The only difference between the discard() and


remove() 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.
- clear() method also can be used, to remove all
elements.
Intersection of sets
! Ex:
setx = set(["green", "blue"])
sety = set(["blue", "yellow"])
setz = setx & sety
print(setz)
#print(setx & sety)
#print(setx.intersection(sety))

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:

setx = set(["green", "blue"])


sety = set(["blue", "yellow", "green"])
c = setx.copy()
print(c)

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.

tup1 = ('physics', 'chemistry', 1997, 2000)


tup2 = (1, 2, 3, 4, 5 )
tup3 = 'a', 'b', 'c', 'd'
tup4 = (1,"a",[3,4],(1,2,3))
print tup4[2] # [3,4]
print tup4[2][0] #3
! Havingone element within parentheses is
not enough. We will need a trailing
comma to indicate that it is in fact a tuple.

! 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.

!L = ('spam', 'Spam', 'SPAM!')


len(tuple)
! Ex:
tuple1, tuple2 = (123, 'xyz', 'zara'), (456, 'abc')
print("First tuple length : ", len(tuple1))
print("Second tuple length : ", len(tuple2))

Output:
First tuple length : 3
Second tuple length : 2
max(tuple)
! Ex:

tuple1, tuple2 = ('xyz', 'zara', 'abc'), (456, 700,


200)
print("Max value element : ", max(tuple1))
print("Max value element : ", max(tuple2))

Output:
Max value element : zara
Max value element : 700
min(tuple)
! Ex:

tuple1, tuple2 = ('xyz', 'zara', 'abc'), (456, 700,


200)
print("Max value element : ", min(tuple1))
print("Max value element : ", min(tuple2))

Output:
Max value element : abc
Max value element : 200
tuple(seq)
! Ex:

aList = [123, 'xyz', 'zara', 'abc']


aTuple = tuple(aList)
print("Tuple elements : ", aTuple)

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:

for name in ('abc','xyz'):


print("Hello",name)

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:

d = dict([('jan', 1), ('feb', 2), ('march', 3)])


print(d['feb'])
! If you have data that doesn't change,
implementing it as tuple will guarantee
that it remains write-protected.
l=[1,2,(3,4),"hello"]
l[2]=l[2]+(4,)
print(l)
l[2]=(2,1,2)
print(l)
del l[2]
#l[3]=[1,2]
print(l)
Output:
[1, 2, (3, 4, 4), 'hello']
[1, 2, (2, 1, 2), 'hello']
[1, 2, 'hello']
l=(1,2,(3,4),[1,2],"hello")
l=l+(4,)
print(l)
l[3].append(4)
print(l)
! Output:

(1, 2, (3, 4), [1, 2], 'hello', 4)


(1, 2, (3, 4), [1, 2, 4], 'hello', 4)
Problem:
! You are required to write a program to sort the (name,
age, height) tuples by ascending order where name is
string, age and height are numbers.
1: Sort based on name;
2: Then sort based on age;
3: Then sort by score.
The priority is that name > age > score. If the following
tuples are given as input to the program:
Tom,19,80
John,20,90
Jony,17,91
Jony,17,93
Then, the output of the program should be:
[('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'),
('Tom', '19', '80')]
from operator import itemgetter, attrgetter
l = []
while True:
s = raw_input()
if not s:
break
l.append(tuple(s.split(",")))
print sorted(l, key=itemgetter(0,1,2))

You might also like