SlideShare a Scribd company logo
Computer Science with Python
Class: XII
Unit I: Computational Thinking and Programming -2
Chapter 1: Review of Python basics II (Revision Tour Class XI)
Mr. Vikram Singh Slathia
PGT Computer Science
Python
• In Slide I, we have learned about Python basic. In this s l i d e
we a re going to understand following concept with reference to
Python
 Strings
 Lists
 Tuples
 Dictionaries
String
Strings are arrays of bytes representing Unicode characters.
However, Python does not have a character data type, a single
character is simply a string with a length of 1. Square brackets
can be used to access elements of the string.
Strings in Python can be created using single quotes or double
quotes or even triple quotes.
# Creating a String with single Quotes
String1 = 'Welcome to World'
print("String with the use of Single Quotes: ")
print(String1)
# Creating a String with double Quotes
String1 = "I'm a boy"
print("nString with the use of Double Quotes: ")
print(String1)
# Creating a String with triple Quotes
String1 = '''I'm a boy'''
print("nString with the use of Triple Quotes: ")
print(String1)
# Creating String with triple Quotes allows multiple lines
String1 = '''India
For
Life'''
print("nCreating a multiline String: ")
print(String1)
Input ( ) always return input
in the form of a string.
String Literal
1. By assigning value directly to the variable
2. By taking Input
String Operators
There are 2operators that can be used to work upon
strings + and *.
» + (it is used to join two strings)
• “tea” + “pot” result “teapot”
• “1” + “2” result “12”
• “123” + “abc” result “123abc”
» * (it is used to replicate the string)
• 5*”@” result “@@@@@”
• “go!” * 3 result “go!go!go!”
String Slicing
• Look at following examples carefully-
word = “RESPONSIBILITY”
word[ 0 : 14 ] result ‘RESPONSIBILITY’
word[ 0 : 3] result ‘RES’
word[ 2 : 5 ] result ‘SPO’
word[ -7 : -3 ] result ‘IBIL’
word[ : 14 ] result ‘RESPONSIBILITY’
word[ : 5 ] result ‘RESPO’
word[ 3 : ] result ‘PONSIBILITY’
llhjh 1 2 3 4 5 6 7 8 9 10 11 12 13
E S P O N S I B I L I T Y
-14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
String Functions
• string.Isdecimal Returns true if all characters in a string are decimal
• String.Isalnum Returns true if all the characters in a given string are alphanumeric.
• string.Istitle Returns True if the string is a titlecased string
• String.partition splits the string at the first occurrence of the separator and returns a
tuple.
• String.Isidentifier Check whether a string is a valid identifier or not.
• String.len Returns the length of the string.
• String.rindex Returns the highest index of the substring inside the string if
substring is found.
• String.Max Returns the highest alphabetical character in a string.
• String.min Returns the minimum alphabetical character in a string.
• String.splitlines Returns a list of lines in the string.
• string.capitalize Return a word with its first character capitalized.
• string.find Return the lowest indexin a sub string.
• string.rfind find the highest index.
• string.count Return the number of (non-overlapping) occurrences of substring
sub in string
• string.lower Return a copy of s, but with upper case letters converted to lower
case.
• string.split Return a list of the words of the string,If the optional second
argument sep is absent or None
• string.rsplit() Return a list of the words of the string s, scanning s from the end.
• rpartition() Method splits the given string into three parts
• string.splitfields Return a list of the words of the string when only used with two
arguments.
• string.strip() It return a copy of the string with both leading and trailing
characters removed
• string.lstrip Return a copy of the string with leading characters removed.
• string.rstrip Return a copy of the string with trailing characters removed.
• string.swapcase Converts lower case letters to upper case and vice versa.
• string.upper lower case letters converted to upper case.
List
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store
collections of data, the other 3 are Tuple, Set, and Dictionary,
all with different qualities and usage.
Important Points:
➔ List is represented by square brackets [ ]
➔ List items are ordered, changeable, and allow duplicate values.
➔ List items are indexed, the first item has index [0], the second
item has index [1] etc.
➔ When we say that lists are ordered, it means that the items have a
defined order, and that order will not change.
➔ If you add new items to a list, the new items will be placed at the
end of the list.
For ex -
• [ ] Empty list
• [1, 2, 3] integers list
• [1, 2.5, 5.6, 9] numbers list (integer and float)
• [ ‘a’, ‘b’, ‘c’] characters list
• [‘a’, 1, ‘b’, 3.5, ‘zero’] mixed values list
• L = [ 3, 4, [ 5, 6 ], 7] Nested List
In Python, only list and dictionary are mutable data types, rest
of all the data types are immutable data types.
List slicing
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[:])
Output
['o', 'g', 'r']
['p', 'r', 'o', 'g']
['a', 'm', 'i', 'z']
['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z']
append() and extend() method
We can add one item to a list using the append() method or
add several items using extend() method.
# Appending and Extending lists in Python
odd = [1, 3, 5] Output
odd.append(7)
print(odd) [1, 3, 5, 7]
odd.extend([9, 11, 13])
print(odd) [1, 3, 5, 7, 9, 11, 13]
Operation of + and * operator
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.
# Concatenating and repeating lists
odd = [1, 3, 5] Output
print(odd + [9, 7, 5]) [1, 3, 5, 9, 7, 5]
print(["re"] * 3) ['re', 're', 're']
insert() Method
Demonstration of list insert() method
odd = [1, 9] Output
odd.insert(1,3)
print(odd) [1, 3, 9]
odd[2:2] = [5, 7]
print(odd) [1, 3, 5, 7, 9]
Delete/Remove List Elements
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']
• We can delete one or more items from a list using the
keyword del. It can even delete the list entirely.
del my_list[2] Output: ['p', 'r', 'b', 'l', 'e', 'm']
• We can use remove() method to remove the given item
my_list.remove('p') Output: ['r', 'o', 'b', 'l', 'e', 'm']
• The pop() method removes and returns the last item if
the index is not provided. This helps us implement lists
as stacks (first in, last out data structure).
print(my_list.pop(1)) Output: 'o'
• We can also use the clear() method to empty a list.
my_list.clear()
print(my_list) Output: []
Python List Methods
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 the 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
List Membership Test
We can test if an item exists in a list or not, using the keyword in.
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']
print('p' in my_list) Output: True
print('a' in my_list) Output: False
print('c' not in my_list) Output: True
Iterating Through a List
Using a for loop we can iterate through each item in a
list.
for fruit in ['apple','banana','mango']:
print("I like",fruit)
Output
I like apple
I like banana
I like mango
Difference between a List and a String
• Main difference between a List and a string is that
string is immutable whereas list is mutable.
• Individual values in string can’t be change whereas it is
possible with list.
Tuple
Tuples are used to store multiple items in a single variable.
Tuple is one of 4 built-in data types in Python used to store
collections of data, the other 3 are List, Set, and Dictionary, all
with different qualities and usage.
◦ A tuple is a collection which is ordered and unchangeable.
◦ Tuples are written with parentheses (), separated by commas.
◦ Tuple is an immutable sequence whose values can not be
changed.
Creation of Tuple
Look at following examples of tuple creation carefully:
Empty tuple my_tuple = ()
Tuple having integers my_tuple = (1, 2, 3)
Tuple with mixed datatypes my_tuple = (1, "Hello", 3.4)
nested tuple my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
Tuple creation from list
Tuple creation from string
Creation of Tuple
tuple() function is used to create a tuple from other
sequences. See examples-
Tuple creation from input
All these elements are of character type. To have
these in different types, need to write following
statement.-
Tuple=eval(input(“Enter elements”))
Accessing a Tuple
• In Python, the process of tuple accessing is same as with list.
Like a list, we can access each and every element of a tuple.
• Similarity with List- like list, tuple also has index. All
functionality of a list and a tuple is same except mutability.
Forward index
Tuple
Backward index
• len ( ) function is used to get the length of tuple.
0 1 2 3 4 5 6 7 8 9 10 11 12 13
R E S P O N S I B I L I T Y
-14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Accessing a Tuple
• Indexing and Slicing:
• T[ i ] returns the item present at index i.
• T[ i : j ] returns a new tuple having all the
items of T from index i to j.
• T [ i : j : n ] returns a new tuple having difference of
n elements of T from index i to j.
Accessing a Tuple
• Accessing Individual elements-
• Traversal of a Tuple –
for <item> in <tuple>:
#to process every element.
OUTPU
T
Tuple will show till last element of list
irrespective of upper limit.
Every alternate element will be
shown.
Every third element will be
shown.
Tuple Slicing
Dictionary
Dictionaries are mutable, unordered collections with elements in
the form of a key:value pair that associate keys to value.
Dictionaries are also called associative array or mappings or
hashes.
To create a dictionary, you need to include the key:value pair
in curly braces.
Syntax:
<dictionary_name> ={<Key>:<Value>,<Key>:<Value>...}
Dictionary Creation
teachers={“Rajeev”: “Math”, “Ajay”: “Physics”, “Karan”: “CS”}
In above given example :
Name of the dictionary: teachers
Key-value pair Key Value
“Rajeev”:”Math” “Rajeev” “Math”
“Ajay”:”Physics” “Ajay” “Physics”
“Karan”:”CS” “Karan” “CS”
# this is an empty dictionary without any element.
Dict1= { }
Point to remember
◦ Keys should always be of immutable type.
◦ If you try to make keys as mutable, python shown error in
it.
◦ Internally, dictionaries are indexed on the basis of key.
Accessing a Dictionary
• To access a value from dictionary, we need to use key
similarly as we use an index to access a value from a list.
• We get the key from the pair of Key: value.
Syntax:
<dictionary_name> [key]
Here, notable thing is that every key of each
pair of dictionary d is coming in k variable of
loop. After this we can take output with the
given format and with print statement.
Traversal of a Dictionary
• To traverse a Dictionary, we use for loop. Syntax is-
for <item> in <dictionary>:
• To access key and value we need to use keys() and
values().
for example-
d.keys( ) function will display only key.
d.values ( ) function will display value only.
Creation of a Dictionary with the pair of name and value:
dict( ) constructor is used to create dictionary with the pairs
of key and value. There are various methods for this-
I. By passing Key:value pair as an argument:
The point to be noted is that here no inverted commas
were placed in
argument but they came automatically in dictionary.
II. By specifying Comma-separated key:value pair-
By passing tuple of
tuple
By passing tuple
of a list
By passing
List
III. By specifying Keys and values separately:
For this, we use zip() function in dict ( ) constructor-
IV. By giving Key:value pair in the form of separate sequence:
Adding an element in Dictionary
Nesting in Dictionary
look at the following example carefully in which element of a
dictionary is a dictionary itself.
Updation in a Dictionary
following syntax is used to update an element in Dictionary-
<dictionary>[<ExistingKey>]=<value>
Program to create a dictionary containing names of employee as
key and their salary as value.
output
Value did not return after
deletion.
Deletion of an element from a Dictionary
following two syntaxes can be used to delete an element form
a Dictionary. For deletion, key should be there otherwise
python will give error.
1. Del <dictionary>[<key>]
It only deletes the value and does not return deleted
value.
2. <dictionary>.pop(<key>)
It returns the deleted value after deletion.
<key> not in
<dictionary>
<key> in
<dictionary>
* in and not in
does not apply on
values, they can
only work with
keys.
Detection of an element from a Dictionary
Membership operator is used to detect presence of an element
in a Dictionary.
it gives true on finding the key
otherwise gives false.
it gives true on not finding the key
otherwise gives false.
json.dumps(<>,indent=
<n>)
Pretty Printing of a Dictionary
To print a Dictionary in a beautify manner, we need to
import json module.
After that following syntax of dumps ( ) will be used.
Program to create a dictionary by counting words in a line
Here a
dictionary is
created of
words and
their
frequency.
Dictionary Function and Method
1. len( ) Method : it tells the length of dictionary.
2. clear( ) Method : it empties the dictionary.
3. get( ) Method : it returns value of the given key.
4. items( ) Method : it returns all items of a dictionary in the
form of tuple of (key:value).
5. keys( ) Method : it returns list of dictionary keys.
6. values( ) Method : it returns list of dictionary values.
7. Update ( ) Method: This function merge the pair of key:value
of a dictionary into other dictionary.
Change and addition in this is possible as
per need.
Sorting
Sorting refer to arrangement of element in specific order.
Ascending or descending
In our syllabus there are only two sorting techniques:
1. Bubble Sort
The basic idea of bubble sort is to compare two adjoining values and
exchange them if they are not in proper order.
2. Insertion Sort
It is a sorting algorithm that builds a sorted list one element at a
time from the unsorted list by inserting the element at its
correct position in sorted list.
It take maximum n-1 passes to sort all the elements of an n-size array.
For reference you check out online
• https://www.programiz.com/python-
programming/first-program
• https://www.w3schools.com/python/
default.asp
Python Revision Tour of Class XI is covered.
In next Slide we are going to Discuss topic:
Working with Function

More Related Content

PDF
Python revision tour i
PPTX
Chapter 02 functions -class xii
PPTX
Chapter 15 Lists
PPTX
Chapter 8 getting started with python
PPTX
Chapter 16 Dictionaries
PPTX
Chapter 9 python fundamentals
PPTX
Chapter 17 Tuples
PDF
Python strings
Python revision tour i
Chapter 02 functions -class xii
Chapter 15 Lists
Chapter 8 getting started with python
Chapter 16 Dictionaries
Chapter 9 python fundamentals
Chapter 17 Tuples
Python strings

What's hot (20)

PPTX
Python Revision Tour.pptx class 12 python notes
PDF
Chapter Functions for grade 12 computer Science
PPTX
Chapter 08 data file handling
PDF
Python libraries
PPTX
DATA STRUCTURE CLASS 12 .pptx
PPTX
Structure in C
PPTX
Data types in python
PPTX
File handling in Python
PPTX
Chapter 14 strings
PDF
Revised Data Structure- STACK in Python XII CS.pdf
PPTX
11 Unit 1 Chapter 02 Python Fundamentals
PPTX
Python dictionary
PPTX
Linked list
PPTX
Conditional Statement in C Language
PPTX
Chapter 03 python libraries
PPTX
arrays and pointers
PPT
PPTX
Conditional and control statement
PDF
Python file handling
Python Revision Tour.pptx class 12 python notes
Chapter Functions for grade 12 computer Science
Chapter 08 data file handling
Python libraries
DATA STRUCTURE CLASS 12 .pptx
Structure in C
Data types in python
File handling in Python
Chapter 14 strings
Revised Data Structure- STACK in Python XII CS.pdf
11 Unit 1 Chapter 02 Python Fundamentals
Python dictionary
Linked list
Conditional Statement in C Language
Chapter 03 python libraries
arrays and pointers
Conditional and control statement
Python file handling
Ad

Similar to Python revision tour II (20)

PPTX
11 Introduction to lists.pptx
PDF
Python Basics it will teach you about data types
PDF
Processing data with Python, using standard library modules you (probably) ne...
PDF
Python Data Types (1).pdf
PDF
Python Data Types.pdf
DOCX
XI_CS_Notes for strings.docx
PDF
ppt notes python language operators and data
PPTX
Data structures in Python
PPTX
Python Workshop
PPTX
Data Structures in Python
PPTX
dataStructuresInPython.pptx
PPT
Data types usually used in python for coding
PPT
02python.ppt
PPT
02python.ppt
PPTX
UNIT-3 python and data structure alo.pptx
PDF
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
PPTX
PRESENTATION ON STRING, LISTS AND TUPLES IN PYTHON.pptx
PPTX
Python data type
PPT
Getting started in Python presentation by Laban K
PPTX
11 Introduction to lists.pptx
Python Basics it will teach you about data types
Processing data with Python, using standard library modules you (probably) ne...
Python Data Types (1).pdf
Python Data Types.pdf
XI_CS_Notes for strings.docx
ppt notes python language operators and data
Data structures in Python
Python Workshop
Data Structures in Python
dataStructuresInPython.pptx
Data types usually used in python for coding
02python.ppt
02python.ppt
UNIT-3 python and data structure alo.pptx
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
PRESENTATION ON STRING, LISTS AND TUPLES IN PYTHON.pptx
Python data type
Getting started in Python presentation by Laban K
Ad

More from Mr. Vikram Singh Slathia (13)

PDF
Marks for Class X Board Exams 2021 - 01/05/2021
PPT
Parallel Computing
PPTX
Online exam series
PDF
Online examination system
PPTX
Parallel sorting
DOCX
Changing education scenario of india
PPTX
PPTX
Multiprocessor system
PDF
Sarasvati Chalisa
DOCX
Save girl child to save your future
PPTX
 Reuse Plastic Bottles.
PPTX
5 Pen PC Technology (P-ISM)
Marks for Class X Board Exams 2021 - 01/05/2021
Parallel Computing
Online exam series
Online examination system
Parallel sorting
Changing education scenario of india
Multiprocessor system
Sarasvati Chalisa
Save girl child to save your future
 Reuse Plastic Bottles.
5 Pen PC Technology (P-ISM)

Recently uploaded (20)

PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PDF
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
PPTX
NOI Hackathon - Summer Edition - GreenThumber.pptx
PPTX
How to Manage Bill Control Policy in Odoo 18
PDF
Landforms and landscapes data surprise preview
PPTX
Odoo 18 Sales_ Managing Quotation Validity
DOCX
UPPER GASTRO INTESTINAL DISORDER.docx
PDF
5.Universal-Franchise-and-Indias-Electoral-System.pdfppt/pdf/8th class social...
PPTX
Congenital Hypothyroidism pptx
PPTX
vedic maths in python:unleasing ancient wisdom with modern code
PDF
English Language Teaching from Post-.pdf
PDF
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
PPTX
Cardiovascular Pharmacology for pharmacy students.pptx
PDF
What Is Coercive Control? Understanding and Recognizing Hidden Abuse
PPTX
Revamp in MTO Odoo 18 Inventory - Odoo Slides
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PPTX
Onica Farming 24rsclub profitable farm business
PPTX
IMMUNIZATION PROGRAMME pptx
PPTX
UNDER FIVE CLINICS OR WELL BABY CLINICS.pptx
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
NOI Hackathon - Summer Edition - GreenThumber.pptx
How to Manage Bill Control Policy in Odoo 18
Landforms and landscapes data surprise preview
Odoo 18 Sales_ Managing Quotation Validity
UPPER GASTRO INTESTINAL DISORDER.docx
5.Universal-Franchise-and-Indias-Electoral-System.pdfppt/pdf/8th class social...
Congenital Hypothyroidism pptx
vedic maths in python:unleasing ancient wisdom with modern code
English Language Teaching from Post-.pdf
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Cardiovascular Pharmacology for pharmacy students.pptx
What Is Coercive Control? Understanding and Recognizing Hidden Abuse
Revamp in MTO Odoo 18 Inventory - Odoo Slides
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Onica Farming 24rsclub profitable farm business
IMMUNIZATION PROGRAMME pptx
UNDER FIVE CLINICS OR WELL BABY CLINICS.pptx
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...

Python revision tour II

  • 1. Computer Science with Python Class: XII Unit I: Computational Thinking and Programming -2 Chapter 1: Review of Python basics II (Revision Tour Class XI) Mr. Vikram Singh Slathia PGT Computer Science
  • 2. Python • In Slide I, we have learned about Python basic. In this s l i d e we a re going to understand following concept with reference to Python  Strings  Lists  Tuples  Dictionaries
  • 3. String Strings are arrays of bytes representing Unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets can be used to access elements of the string. Strings in Python can be created using single quotes or double quotes or even triple quotes. # Creating a String with single Quotes String1 = 'Welcome to World' print("String with the use of Single Quotes: ") print(String1)
  • 4. # Creating a String with double Quotes String1 = "I'm a boy" print("nString with the use of Double Quotes: ") print(String1) # Creating a String with triple Quotes String1 = '''I'm a boy''' print("nString with the use of Triple Quotes: ") print(String1) # Creating String with triple Quotes allows multiple lines String1 = '''India For Life''' print("nCreating a multiline String: ") print(String1)
  • 5. Input ( ) always return input in the form of a string. String Literal 1. By assigning value directly to the variable 2. By taking Input
  • 6. String Operators There are 2operators that can be used to work upon strings + and *. » + (it is used to join two strings) • “tea” + “pot” result “teapot” • “1” + “2” result “12” • “123” + “abc” result “123abc” » * (it is used to replicate the string) • 5*”@” result “@@@@@” • “go!” * 3 result “go!go!go!”
  • 7. String Slicing • Look at following examples carefully- word = “RESPONSIBILITY” word[ 0 : 14 ] result ‘RESPONSIBILITY’ word[ 0 : 3] result ‘RES’ word[ 2 : 5 ] result ‘SPO’ word[ -7 : -3 ] result ‘IBIL’ word[ : 14 ] result ‘RESPONSIBILITY’ word[ : 5 ] result ‘RESPO’ word[ 3 : ] result ‘PONSIBILITY’ llhjh 1 2 3 4 5 6 7 8 9 10 11 12 13 E S P O N S I B I L I T Y -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
  • 8. String Functions • string.Isdecimal Returns true if all characters in a string are decimal • String.Isalnum Returns true if all the characters in a given string are alphanumeric. • string.Istitle Returns True if the string is a titlecased string • String.partition splits the string at the first occurrence of the separator and returns a tuple. • String.Isidentifier Check whether a string is a valid identifier or not. • String.len Returns the length of the string. • String.rindex Returns the highest index of the substring inside the string if substring is found. • String.Max Returns the highest alphabetical character in a string. • String.min Returns the minimum alphabetical character in a string. • String.splitlines Returns a list of lines in the string. • string.capitalize Return a word with its first character capitalized. • string.find Return the lowest indexin a sub string.
  • 9. • string.rfind find the highest index. • string.count Return the number of (non-overlapping) occurrences of substring sub in string • string.lower Return a copy of s, but with upper case letters converted to lower case. • string.split Return a list of the words of the string,If the optional second argument sep is absent or None • string.rsplit() Return a list of the words of the string s, scanning s from the end. • rpartition() Method splits the given string into three parts • string.splitfields Return a list of the words of the string when only used with two arguments. • string.strip() It return a copy of the string with both leading and trailing characters removed • string.lstrip Return a copy of the string with leading characters removed. • string.rstrip Return a copy of the string with trailing characters removed. • string.swapcase Converts lower case letters to upper case and vice versa. • string.upper lower case letters converted to upper case.
  • 10. List Lists are used to store multiple items in a single variable. Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage. Important Points: ➔ List is represented by square brackets [ ] ➔ List items are ordered, changeable, and allow duplicate values. ➔ List items are indexed, the first item has index [0], the second item has index [1] etc.
  • 11. ➔ When we say that lists are ordered, it means that the items have a defined order, and that order will not change. ➔ If you add new items to a list, the new items will be placed at the end of the list. For ex - • [ ] Empty list • [1, 2, 3] integers list • [1, 2.5, 5.6, 9] numbers list (integer and float) • [ ‘a’, ‘b’, ‘c’] characters list • [‘a’, 1, ‘b’, 3.5, ‘zero’] mixed values list • L = [ 3, 4, [ 5, 6 ], 7] Nested List In Python, only list and dictionary are mutable data types, rest of all the data types are immutable data types.
  • 12. List slicing 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[:]) Output ['o', 'g', 'r'] ['p', 'r', 'o', 'g'] ['a', 'm', 'i', 'z'] ['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z']
  • 13. append() and extend() method We can add one item to a list using the append() method or add several items using extend() method. # Appending and Extending lists in Python odd = [1, 3, 5] Output odd.append(7) print(odd) [1, 3, 5, 7] odd.extend([9, 11, 13]) print(odd) [1, 3, 5, 7, 9, 11, 13]
  • 14. Operation of + and * operator 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. # Concatenating and repeating lists odd = [1, 3, 5] Output print(odd + [9, 7, 5]) [1, 3, 5, 9, 7, 5] print(["re"] * 3) ['re', 're', 're']
  • 15. insert() Method Demonstration of list insert() method odd = [1, 9] Output odd.insert(1,3) print(odd) [1, 3, 9] odd[2:2] = [5, 7] print(odd) [1, 3, 5, 7, 9]
  • 16. Delete/Remove List Elements my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm'] • We can delete one or more items from a list using the keyword del. It can even delete the list entirely. del my_list[2] Output: ['p', 'r', 'b', 'l', 'e', 'm'] • We can use remove() method to remove the given item
  • 17. my_list.remove('p') Output: ['r', 'o', 'b', 'l', 'e', 'm'] • The pop() method removes and returns the last item if the index is not provided. This helps us implement lists as stacks (first in, last out data structure). print(my_list.pop(1)) Output: 'o' • We can also use the clear() method to empty a list. my_list.clear() print(my_list) Output: []
  • 18. Python List Methods 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 the 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
  • 19. List Membership Test We can test if an item exists in a list or not, using the keyword in. my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm'] print('p' in my_list) Output: True print('a' in my_list) Output: False print('c' not in my_list) Output: True
  • 20. Iterating Through a List Using a for loop we can iterate through each item in a list. for fruit in ['apple','banana','mango']: print("I like",fruit) Output I like apple I like banana I like mango
  • 21. Difference between a List and a String • Main difference between a List and a string is that string is immutable whereas list is mutable. • Individual values in string can’t be change whereas it is possible with list.
  • 22. Tuple Tuples are used to store multiple items in a single variable. Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage. ◦ A tuple is a collection which is ordered and unchangeable. ◦ Tuples are written with parentheses (), separated by commas. ◦ Tuple is an immutable sequence whose values can not be changed.
  • 23. Creation of Tuple Look at following examples of tuple creation carefully: Empty tuple my_tuple = () Tuple having integers my_tuple = (1, 2, 3) Tuple with mixed datatypes my_tuple = (1, "Hello", 3.4) nested tuple my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
  • 24. Tuple creation from list Tuple creation from string Creation of Tuple tuple() function is used to create a tuple from other sequences. See examples-
  • 25. Tuple creation from input All these elements are of character type. To have these in different types, need to write following statement.- Tuple=eval(input(“Enter elements”))
  • 26. Accessing a Tuple • In Python, the process of tuple accessing is same as with list. Like a list, we can access each and every element of a tuple. • Similarity with List- like list, tuple also has index. All functionality of a list and a tuple is same except mutability. Forward index Tuple Backward index • len ( ) function is used to get the length of tuple. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 R E S P O N S I B I L I T Y -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
  • 27. Accessing a Tuple • Indexing and Slicing: • T[ i ] returns the item present at index i. • T[ i : j ] returns a new tuple having all the items of T from index i to j. • T [ i : j : n ] returns a new tuple having difference of n elements of T from index i to j.
  • 28. Accessing a Tuple • Accessing Individual elements- • Traversal of a Tuple – for <item> in <tuple>: #to process every element.
  • 30. Tuple will show till last element of list irrespective of upper limit. Every alternate element will be shown. Every third element will be shown. Tuple Slicing
  • 31. Dictionary Dictionaries are mutable, unordered collections with elements in the form of a key:value pair that associate keys to value. Dictionaries are also called associative array or mappings or hashes. To create a dictionary, you need to include the key:value pair in curly braces. Syntax: <dictionary_name> ={<Key>:<Value>,<Key>:<Value>...}
  • 32. Dictionary Creation teachers={“Rajeev”: “Math”, “Ajay”: “Physics”, “Karan”: “CS”} In above given example : Name of the dictionary: teachers Key-value pair Key Value “Rajeev”:”Math” “Rajeev” “Math” “Ajay”:”Physics” “Ajay” “Physics” “Karan”:”CS” “Karan” “CS”
  • 33. # this is an empty dictionary without any element. Dict1= { } Point to remember ◦ Keys should always be of immutable type. ◦ If you try to make keys as mutable, python shown error in it. ◦ Internally, dictionaries are indexed on the basis of key.
  • 34. Accessing a Dictionary • To access a value from dictionary, we need to use key similarly as we use an index to access a value from a list. • We get the key from the pair of Key: value. Syntax: <dictionary_name> [key]
  • 35. Here, notable thing is that every key of each pair of dictionary d is coming in k variable of loop. After this we can take output with the given format and with print statement. Traversal of a Dictionary • To traverse a Dictionary, we use for loop. Syntax is- for <item> in <dictionary>:
  • 36. • To access key and value we need to use keys() and values(). for example- d.keys( ) function will display only key. d.values ( ) function will display value only.
  • 37. Creation of a Dictionary with the pair of name and value: dict( ) constructor is used to create dictionary with the pairs of key and value. There are various methods for this- I. By passing Key:value pair as an argument: The point to be noted is that here no inverted commas were placed in argument but they came automatically in dictionary. II. By specifying Comma-separated key:value pair-
  • 38. By passing tuple of tuple By passing tuple of a list By passing List III. By specifying Keys and values separately: For this, we use zip() function in dict ( ) constructor- IV. By giving Key:value pair in the form of separate sequence:
  • 39. Adding an element in Dictionary
  • 40. Nesting in Dictionary look at the following example carefully in which element of a dictionary is a dictionary itself.
  • 41. Updation in a Dictionary following syntax is used to update an element in Dictionary- <dictionary>[<ExistingKey>]=<value>
  • 42. Program to create a dictionary containing names of employee as key and their salary as value. output
  • 43. Value did not return after deletion. Deletion of an element from a Dictionary following two syntaxes can be used to delete an element form a Dictionary. For deletion, key should be there otherwise python will give error. 1. Del <dictionary>[<key>] It only deletes the value and does not return deleted value. 2. <dictionary>.pop(<key>) It returns the deleted value after deletion.
  • 44. <key> not in <dictionary> <key> in <dictionary> * in and not in does not apply on values, they can only work with keys. Detection of an element from a Dictionary Membership operator is used to detect presence of an element in a Dictionary. it gives true on finding the key otherwise gives false. it gives true on not finding the key otherwise gives false.
  • 45. json.dumps(<>,indent= <n>) Pretty Printing of a Dictionary To print a Dictionary in a beautify manner, we need to import json module. After that following syntax of dumps ( ) will be used.
  • 46. Program to create a dictionary by counting words in a line
  • 47. Here a dictionary is created of words and their frequency.
  • 48. Dictionary Function and Method 1. len( ) Method : it tells the length of dictionary. 2. clear( ) Method : it empties the dictionary. 3. get( ) Method : it returns value of the given key. 4. items( ) Method : it returns all items of a dictionary in the form of tuple of (key:value). 5. keys( ) Method : it returns list of dictionary keys. 6. values( ) Method : it returns list of dictionary values. 7. Update ( ) Method: This function merge the pair of key:value of a dictionary into other dictionary. Change and addition in this is possible as per need.
  • 49. Sorting Sorting refer to arrangement of element in specific order. Ascending or descending In our syllabus there are only two sorting techniques: 1. Bubble Sort The basic idea of bubble sort is to compare two adjoining values and exchange them if they are not in proper order. 2. Insertion Sort It is a sorting algorithm that builds a sorted list one element at a time from the unsorted list by inserting the element at its correct position in sorted list. It take maximum n-1 passes to sort all the elements of an n-size array.
  • 50. For reference you check out online • https://www.programiz.com/python- programming/first-program • https://www.w3schools.com/python/ default.asp
  • 51. Python Revision Tour of Class XI is covered. In next Slide we are going to Discuss topic: Working with Function