Unit I: Computational Thinking and Programming - 2
Chapter-2 Revision Tour -II
Python Revision Tour –II
In this tutorial we will discuss the following topics
S.No. Topics
1 Python: String
2 Python: List
3 Python: Tuple
4 Python: Dictionaries
Page 1 of 20
Unit I: Computational Thinking and Programming - 2
Chapter-2 Revision Tour -II
Python: String
What is String?
A string is a sequence of characters. Strings are basically just a bunch of words.
Strings are immutable. It means that the contents of the string cannot be changed
after it is created.
A literal/constant value to a string can be assigned using a single quotes, double
quotes or triple quotes.
Declaring a string in python
>>>myString = “String Manipulation”
>>>mystring
Output: String Manipulation
Traversing a string:-
Traversing refers to iterating through the elements of a string, one character at a
time. A string can be traversed using: for loop or while loop. For Example:
myname =”Amjad”
for ch in myname:
print (ch, end=‘-‘)
The above code will print:
A-m-j-a-d-
Access String with subscripts:
Let us understand with the help of an example:
myString = “PYTHON”
Page 2 of 20
Unit I: Computational Thinking and Programming - 2
Chapter-2 Revision Tour -II
OUTPUT:
Important points about accessing elements in the strings using subscripts:
Positive Index 0 1 2 3 4 5
myString ‘P’ ‘Y’ ‘T’ ‘H’ ‘O’ ‘N’
Negative Index -6 -5 -4 -3 -2 -1
Positive subscript helps in accessing the string from the beginning
Negative subscript helps in accessing the string from the end.
Subscript 0 or negative n (where n is length of the string) displays the first
element.
Example : A[0] or A[-6] will display ‘P’
Subscript 1 or –ve (n-1) displays the second element.
Page 3 of 20
Unit I: Computational Thinking and Programming - 2
Chapter-2 Revision Tour -II
More on string Slicing:-
The general form is: strName [start : end]
start and end must both be integers
o - The substring begins at index start
o - The substring ends before index end
The letter at index end is not included
Let us understand with the help of an example:
Positive Index 0 1 2 3 4 5 6 7 8 9 10
String A P Y t h o n P r o g
Negative Index -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Lets we consider a string A= ’Python Prog’
S.No. Example OUTPUT Explanation
The print statement prints the
1 print (A [1 : 3]) Yt substring starting from subscript 1
and ending at subscript 2
Prints the substring starting from
2 print (A [3 : ]) hon Prog
subscript 3 to till the end of the string
The print statement extract the
3 print (A [ : 3]) Pyt substring before the third index
starting from the beginning
Omitting both the indices, directs the
python interpreter to extract the
4 print (A [ : ]) Python Prog
entire string starting from 0 till the
last index
For negative indices the python
interpreter counts from the right
5 print (A [-2 : ]) og
side. So the last two letters are
printed.
It extracts the substring form the
beginning. Since the negative index
6 print (A[ : -2]) Python Pr indicates slicing from the end of the
string. So the entire string except the
last two letters is printed.
Page 4 of 20
Unit I: Computational Thinking and Programming - 2
Chapter-2 Revision Tour -II
String methods & built in functions:-
Lets Consider two Strings: str1="Save Earth" and str2='welcome'
Syntax Description Example
len ( ) Return the length of the >>> print (len(str1))
string 10
capitalize ( ) Return the exact copy of >>>print (str2.capitalize())
the string with the first Welcome
letter in upper case
isalnum() Returns True if the string >>>print(str1.isalnum())
contains only letters and FALSE
digit. It returns False ,If The function returns False as
the string contains any space is an alphanumeric
special character like _ , character.
>>>print('Save1Earth'.isalnum())
@,#,* etc.
TRUE
isalpha() Returns True if the string >>> print('Click123'.isalpha())
contains only letters. FALSE
Otherwise return False. >>> print('python'.isalpha())
TRUE
isdigit() Returns True if the string >>>print (str2.isdigit())
contains only numbers. FALSE
Otherwise it returns
False.
lower() Returns the exact copy of >>>print (str1.lower())
the string with all the save earth
letters in lowercase.
islower() Returns True if the string >>>print (str2.islower())
is in lowercase. TRUE
isupper() Returns True if the string >>>print (str2.isupper())
is in uppercase. FALSE
upper() Returns the exact copy of >>>print (str2.upper())
the string with all letters WELCOME
in uppercase.
Page 5 of 20
Unit I: Computational Thinking and Programming - 2
Chapter-2 Revision Tour -II
Python: List
The list is a type of data in Python used to store multiple objects.
It is an ordered and mutable collection of comma-separated items between
square brackets [ ]
Example:
myList = [10, None, True, "I am a student", 250, 0]
Lists can be indexed and updated, Examples:
Here, index 1 (None) updated with value ‘?’
Lists can be nested
Example:
Output: [1, 'a', ['list', 64, [0, 1], False]]
Page 6 of 20
Unit I: Computational Thinking and Programming - 2
Chapter-2 Revision Tour -II
List elements and lists can be deleted
Example:
Lists can be iterated through using the for loop
Example:
The len() function may be used to check the list's length
Example:
If you have a list l1, then the following assignment: l2 = l1 does not make a
copy of the l1 list, but makes the variables l1 and l2 point to one and the
same list in memory.
Example:
Page 7 of 20
Unit I: Computational Thinking and Programming - 2
Chapter-2 Revision Tour -II
If you want to copy a list or part of the list, you can do it by performing
slicing:
Example
You can use negative indices to perform slices, too.
Example:
The start and end parameters are optional when performing a slice:
Example:
Page 8 of 20
Unit I: Computational Thinking and Programming - 2
Chapter-2 Revision Tour -II
You can delete slices using the del instruction:
Example:
You can test if some items exist in a list or not using the keywords in and not
in, Example:
Page 9 of 20
Unit I: Computational Thinking and Programming - 2
Chapter-2 Revision Tour -II
Python: Tuple
Tuples are ordered and unchangeable (immutable) collections of data. They can
be thought of as immutable lists. They are written in round brackets ( ):
Example:
OUTPUT: (1, 2, True, 'a student', (3, 4), [5, 6], None)
OUTPUT: [1, 2, True, 'a tupleString', (3, 4), [5, 6], None]
Each tuple element may be of a different type (i.e., integers, strings, booleans, etc.).
What is more, tuples can contain other tuples or lists (and the other way round).
You can create an empty tuple like this:
Example:
OUTPUT: <class 'tuple'>
Page 10 of 20
Unit I: Computational Thinking and Programming - 2
Chapter-2 Revision Tour -II
A one-element tuple may be created as follows:
Example:
Note: If you remove the comma, you will tell Python interpreter to create a variable,
not a tuple:
OUTPUT: <class 'tuple'>
OUTPUT: <class 'int'>
You can access tuple elements by indexing them:
Example:
OUTPUT: [3, 4]
Page 11 of 20
Unit I: Computational Thinking and Programming - 2
Chapter-2 Revision Tour -II
Tuples are immutable, which means you cannot change their elements (you
cannot append tuples, or modify, or remove tuple elements).
The following snippet will cause an exception:
TypeError: 'tuple' object does not support item assignment
However, you can delete a tuple as a whole:
NameError: name 'myTuple' is not defined
Tuple can be iterated through using the for loop
You can loop through a tuple elements
OUTPUT: 1 2 3
Page 12 of 20
Unit I: Computational Thinking and Programming - 2
Chapter-2 Revision Tour -II
check if a specific element is (not)present in a tuple
OUTPUT: False
True
use the len() function to check how many elements there are in a tuple
OUTPUT: Length of given tuple is: 4
or even join/multiply tuples
OUTPUT:
join of t1 and t2 is: (1, 2, 3, 1, 2, 3, 4)
Multiplication of tuple t3 by 2: (1, 2, 3, 5, 1, 2, 3, 5)
Page 13 of 20
Unit I: Computational Thinking and Programming - 2
Chapter-2 Revision Tour -II
You can also create a tuple using a Python built-in function called tuple(). This
is particularly useful when you want to convert a certain iterable (e.g., a list,
range, string, etc.) to a tuple:
OUTPUT: (1, 2, 'computer')
OUTPUT: [2, 4, 6]
OUTPUT: <class 'list'>
OUTPUT: (2, 4, 6)
OUTPUT: <class 'tuple'>
By the same fashion, when you want to convert an iterable to a list, you can
use a Python built-in function called list():
OUTPUT: <class 'list'>
Page 14 of 20
Unit I: Computational Thinking and Programming - 2
Chapter-2 Revision Tour -II
Python: Dictionaries
Dictionaries are unordered, changeable (mutable), and indexed collections of
data. (Note: In Python 3.6x dictionaries have become ordered by default).
Each dictionary is a set of key: value pairs.
You can create it by using the following Syntax:
my_dict = {'key1': 'value1','key2': 'value2','key3': 'value3'…'keyn': 'valuen'}
Dictionary Keys
A dictionary as an unordered set of key: value pairs
Dictionary keys must be unique
o A key in a dictionary is like an index in a list
o Python must know exactly which value you want
Keys can be of any data type
o As long as it is immutable
Dictionary Values
Dictionary keys have many rules, but the values do not have many restrictions
They do not have to be unique
They can be mutable or immutable
To Create Empty Dictionary:
The function dict ( ) is used to create a new dictionary with no items. This
function is called built-in function. OR
We can also create dictionary using { }.
Page 15 of 20
Unit I: Computational Thinking and Programming - 2
Chapter-2 Revision Tour -II
Example:
OUTPUT: { }
To create a dictionary, use curly braces, and a colon (:) to separate keys from
their value
Example:
OUTPUT: {'input': 'keybord', 'output': 'monitor', 'language':
'python', 'os': 'windows- 8'}
In the above example
input, output, language and os are the keys of dictionary
keyboard, monitor, python and windows- 8 are values.
If you want to access a dictionary item, you can do so by making a reference to
its key inside a pair of square brackets.
Example:
OUTPUT: monitor
Page 16 of 20
Unit I: Computational Thinking and Programming - 2
Chapter-2 Revision Tour -II
By using the get() method
Example:
OUTPUT: python
If you want to change the value associated with a specific key, you can do so by
referring to the item's key name in the following way:
Example:
In this example we change the value
associated with output key to printer
(i.e. change monitor to printer)
OUTPUT: printer
To add or remove a key (and the associated value), use the following syntax:
Example:
Page 17 of 20
Unit I: Computational Thinking and Programming - 2
Chapter-2 Revision Tour -II
OUTPUT: Dictionary after adding new value {'input':
'keybord', 'output': 'monitor', 'language': 'python', 'os':
'windows- 8', 'memory': 'HDD'}
Dictionary after deletion {'input': 'keybord', 'output':
'monitor', 'language': 'python', 'os': 'windows- 8'}
You can also insert an item to a dictionary by using the update() method, and
remove the last element by using the popitem() method
Example:
update() method add new pair-value(i.e. ‘network’:’ wi –
fi’ ) to the dictionary and
popitem() remove the last element from the dictionary.
OUTPUT: {'input': 'keybord', 'output': 'monitor', 'language': 'python', 'os':
'windows- 8', 'network': 'wi-fi'}
{'input': 'keybord', 'output': 'monitor', 'language': 'python', 'os': 'windows- 8'}
You can use the for loop to loop through a dictionary
OUTPUT: input
Example:
output
language
os
Page 18 of 20
Unit I: Computational Thinking and Programming - 2
Chapter-2 Revision Tour -II
If you want to loop through a dictionary's keys and values, you can use
the items() method
Example:
OUTPUT: input : keybord
output : monitor
language : python
os : windows- 8
To check if a given key exists in a dictionary, you can use the in keyword:
Example:
OUTPUT: Yes
Page 19 of 20
Unit I: Computational Thinking and Programming - 2
Chapter-2 Revision Tour -II
You can use the del keyword to remove a specific item, or delete a dictionary.
To remove all the dictionary's items, you need to use the clear() method:
Example:
To copy a dictionary, use the copy() method:
Example:
OUTPUT: Copied Dictionary: {'input': 'keybord', 'output':
'monitor', 'language': 'python', 'os': 'windows- 8'}
Page 20 of 20