CSC101 – Introduction to ICT
Sequences
Course Instructors
Dr. Majid Iqbal Khan Dr. Ashfaq Hussain Farooqi Mr. Rizwan Rashid Ms. Sajida Kalsoom
Agenda
What are sequences?
Sequences operations
Types of sequences in Python
Lists
Strings
Tuples
Sets
Dictionary
2
What are Sequences?
Sequences can be consider as container where different items (int, float, object) are
stored
Following are three sequences of length four
Each fruit/number/character in these sequences are called element of the sequence
Sequence s1
Sequence s2 12 3 6 32
Sequence s3 ‘h’ ‘e’ ‘l’ ‘o’
3
Common Operations for Sequence
Concatenation
Repetition
Membership
testing
Indexing Sequence s
Slicing
Other useful 4
operations
Concatenation
Sequence s1 Concatenating Sequence s2
Sequence
s1 and s2
Code: s = s1 + s2 # Concatenates two sequences s1 and s2.
s=
5
Repetition
Sequence s1
Repeat
Sequence s1
3 times
Code: s1 = s1 x n
Or s1 = n x s1 # n copies of sequence s concatenated
s1 =
6
Membership testing
Sequence s
Is a member? Is a member?
False True
Code: x in s # True if element x is in sequence s. Code: x not in s # True if element x is not in sequence s.
Indexing
Element value at index 3 accessed using s[3]
Sequence s (s is the reference variable)
Index: 0 1 2 3 4 5
Element: s[0] s[1] s[2] s[3] s[4] s[5]
Access an ith element in the sequence s - s[i]
Traverses elements from left to right in a for loop. Following code will all I elements in Sequence s
Code: for i in range (0, 6): OR for i in s:
print (s[i]) print (s)
8
Slicing
Sequence s
Index: 0 1 2 3 4 5
Slice sequence s from index i to (j-1)
Code: s[i : j]
For example, s[1 : 5] returns following
sequence
9
Other useful operations
Operation Description
len(s) Length of sequence s, i.e., the number of elements in s.
min(s) Smallest element in sequence s.
max(s) Largest element in sequence s.
sum(s) Sum of all elements in sequence s.
<, <=, >, >=, =, != Compares two sequences.
10
Sequences in Python
Lists Strings Dictionaries
Tuples Sets
11
List
List is one of the important sequences available in Python where different items can be stored
list1 = list() # Create an empty list having name list1
OR list1 = []
num_list = [12, 24, 51, 16, 99]
OR num_list = list([12, 24, 51, 16, 99]) 12 24 51 16 99
str_list = [“Hello”, “Hi”, “World”]
OR str_list = list([“Hello”, “Hi”, “World”]) “Hello” “Hi” “World”
mix_list = [10, “Hello”, “a”, “World”, 15.6]
10 “Hello” “a” “World” 15.6
OR mix_list = list([10, “Hello”, “a”, “World”, 15.6])
List (Cond...)
Following two definitions can only be made using list1 = list() and not with list1 = []
num_list = list(range(3, 6)) # Create a list with elements 3, 4, 5
3 4 5
char_list = list("abcde") # Create a list with characters a, b, c, d
“a” “b” “c” “d” “e”
Basic operations for List
num1 = [2, 4, 6, 8, 10]
num2 = [1, 3, 5, 7, 9] Output
Concatenation print ( num1+num2 ) - [2, 4, 6, 8, 10, 1, 3, 5, 7, 9]
Repetition print ( 2*num1 ) - [2, 4, 6, 8, 10, 2, 4, 6, 8, 10]
Membership print ( 5 in num1 ) - False
testing
Slicing print ( num1[1:3] ) - [4, 6]
Indexing print ( num2[4] ) - 9 14
Basic operations for List
import random
num1 = [2, 4, 6, 8, 10] Output
max print ( max(num1) ) - 10
min print ( min(num1) ) - 2
sum print ( sum(num1) ) - 30
length print ( len(num1) ) - 5
random.shuffle(num1)
shuffle print ( num1 ) - [10, 4, 6, 8, 2]
15
List methods
num1 = [2, 4, 6, 8, 10]
num2 = [1, 3] Output
num1.append(20)
append print ( num1 ) - [2, 4, 6, 8, 10, 20]
num1.insert(5, 4)
Insert(index, element) print ( num1 ) - [2, 4, 6, 8, 10, 4, 20]
num1.extend(num2)
extend print ( num1 ) - [2, 4, 6, 8, 10, 4, 20, 1, 3]
index print ( num1.index(4) ) - 1
print ( num1.count(4) ) - 2
count 16
List methods
num1 = [2, 4, 6, 8, 10, 4, 20, 1, 3] Output
print ( num1.pop(2) ) - 6
pop print ( num1.pop() ) 3
num1.remove(4) - [2, 6, 8, 10, 4, 20, 1, 3]
remove print ( num1 )
num1.reverse()
reverse print ( num1 ) - [3, 1, 20, 4, 10, 8, 6, 4, 2]
num1.sort()
sort print ( num1 ) - [1, 2, 3, 4, 4, 6, 8, 10, 20]
17
Example – storing marks of the students
We have marks of all the students stored in a List. Now I want to
Compute the average score for the class
How many students scored above average
18
Exercise
Write a program that reads unspecified number of integers from user into the list and
displays them in the reverse order in which they were read.
Enter integers for the list or 0 to print the list in reverse order:
6
3
4
5
0
Your entered list is: 5 4 3 6
19
To copy the data in one list to another list,
Copying Lists you have to copy individual elements
from the source list to the target list.
You often need to duplicate a list or part of a list in a program.
In such cases you could attempt to use the assignment statement (=), as follows:
list2 = list1
However, this statement does not copy the contents of the list referenced by list1 to list2;
instead, it merely copies the reference value from list1 to list2.
After this statement, list1 and list2 refer to the same list
20
Copying Lists
The list previously referenced by list2 is no longer referenced; it
becomes garbage.
The memory space occupied by list2 will be automatically collected and
reused by the Python interpreter.
Before the assignment statement, list1 and list2 point to separate memory locations. After the assignment, the
list1 reference value is passed to list2.
Copying Lists
To get a duplicate copy of list1 into list2, you can use:
list2 = [x for x in list1]
or simply:
list2 = [ ] + list1
22
When passing a list to a function,
the contents of the list may change
Passing Lists to Functions after the function call, since a list
is a mutable object.
Since list is an object, passing a list to a function is just like passing an object to a function.
Signature
def printList(lst):
Function
Definition for element in lst:
Body
print(element)
Invoking
Function printList([3, 1, 2, 6])
23
When a function returns
Returning a List from a Function a list, the list’s reference
value is returned.
A function can also return a list.
For example, the following function returns a list that is the reversal of another list.
24
Strings
String is another type of sequence available in Python
Strings can be created, as follows:
s1 = str() # Create an empty string object
s2 = str("Welcome") # Create a string object for Welcome
A simple syntax for creating a string is as follows,
s1 = "" # Same as s1 = str()
s2 = "Welcome" # Same as s2 = str("Welcome")
25
Functions for Strings
All of the basic operations discussed in the context of sequences also apply to
the Stings.
Concatenation
Repetition s = “Welcome” s1 = “Hello”
max(s) => o # since character o has highest ASCII value in the string s
Membership for i in range (0, len(s)): # indexing – iterates the string. Also len() is used
testing
print(s[i])
Slicing s != s1 => True # comparison operators
“come” in s => True # if the string “come” is present in string s
Indexing
26
Testing Strings
Function Description Code
isalnum() Returns True if characters in this string are alphanumeric s = "welcome to python"
and there is at least one character. s.isalnum() => False
isalpha() Returns True if characters in this string are alphabetic and
there is at least one character.
isdigit() Returns True if this string contains only number characters. s = “12356"
s.isdigit() => True
isidentifier() Returns True if this string is a Python identifier.
islower() Returns True if all characters in this string are lowercase s = "welcome to python"
letters and there is at least one character. s.islower() => True
isupper() Returns True if all characters in this string are uppercase
letters and there is at least one character.
isspace() Returns True if this string contains only whitespace s = "welcome to python"
characters. s.isspace() => False 27
Searching for Substrings
Functions Description code
endswith(s1: str) Returns True if the string ends with the substring s1. s = "welcome to python"
startswith(s1: str) Returns True if the string starts with the substring s1. s.endswith("thon") => True
find(s1) Returns the lowest index where s1 starts in this string, s = "welcome to python"
or –1 if s1 is not found in this string.
s.find("become") => -1
rfind(s1) Returns the highest index where s1 starts in this string,
or –1 if s1 is not found in this string.
count(substring) Returns the number of non-overlapping occurrences s = "welcome to python"
of this substring.
s.count("o") => 3
28
Other String functions
Converting String
Methods let you control the capitalization of letters in the string’s copy, or to replace the string
entirely.
Functions: capitalize(), lower(), upper(), swapcase(), replace(old, new)
Stripping Whitespace Characters from a String
Methods to strip whitespace characters from the front, end, or both the front and end of a string.
Functions: lstrip(), rstrip(), strip()
Formatting Strings
Methods to return a formatted string
Functions: center(width), ljust(width), rjust(width), format(items)
29
Checking Palindromes
A string is a palindrome if it reads the same forward and backward. The words “mom,”
“dad,” and “noon,” for instance, are all palindromes.
30