Sequences, Strings and Sets
Sequences, Strings and Sets
Sequences, Strings and Sets
Sequences
• A sequence contains objects that are kept in a
specific order.
• You can identify an object in a sequence by its
index location.
– Strings use quotes, such as 'Hello', "Hello",
'"Hello"‘, """Hello""".
– Lists use square brackets, such as [Tiger,
Coffee, 1,'a', 10.50,'b'].
– Tuples use parentheses, such as (Tiger, Coffee,
1,'a',10.50, 'b').
• Tuples and strings are immutable—they
cannot be modified after they are created.
• A copy of a string or a tuple is created when
you apply an operation to the original string or
tuple.
• A list is mutable; you can append elements,
remove existing elements, or rearrange
elements.
• The three operations that are commonly
applied to sequences are these:
– + will concatenate sequences to make longer
sequences.
– * is used with a numerical digit to repeat the
sequence several times.
– [ ] fetches a particular element from the
sequence (indexing) or a subset of elements from
the sequence (slicing).
Strings
• A string literal can be enclosed in single ('),
double (") or triple quotes (''').
• Strings are immutable in Python; you cannot
modify an existing string object.
k='Hello World!'
k="Hello World!"
k='''
Hello World!
It\' s hot today
Let\'s party '''
• To make the string appear on two lines, you can embed a
newline in the string:
k="Hello World!\nIt's hot“
• If the string literal spans multiple lines, use a backslash as
the last character of a line to indicate that the next line is a
continuation:
k="Hello World!\
It's hot“
string1.py
n=input("Enter your name: ")
l=len(n)
print ("The name entered is", n, "and its length is", l)
Output:
Enter your name: John
The name entered is John and its length is 4
• Example:
ifelse4.py
m=input("Enter marks: ")
if m.isdigit():
print ("Entered data is numeric")
else:
print ("Entered data is not numeric")
Output:
Enter marks: 50
Entered data is numeric
Enter marks: fifty
Entered data is not numeric
• Example:
characterwise.py
s=input("Enter a string: ")
n=len(s)
print ("The first character of", s, "is", s[0])
print ("The entered string will appear character wise as:")
for i in range(0,n):
print (s[i])
print ("The entered string will appear character wise as:")
for i in s:
print (i)
print ("String with its characters sorted is", sorted(s))
print ("String in reverse form is", "".join(reversed(s)))
String Methods Used to Find Substrings in
a String
Method Description
count(s, [start], Returns the number of occurrences of
[end]) substring s in a string. If start or end is
specified, the substring s is searched and
counted within the index range.
find(s, [start], Returns the lowest index in a string where
[end]) substring s is found. The function returns
-1 if the substring is not found.
index(s, [start], Returns the lowest index in a string where
[end]) substring s is found. The function raises
ValueError if the substring is not found.
rfind(s, [start], Returns the highest index in a string
[end]) where substring s is found. It returns -1 if
the substring is not found.
Example
countvowel.py
s=input('Enter a sentence: ')
n=len(s)
c=0
for i in range(0,n):
if(s[i]=='a' or s[i]=='A' or s[i]=='e' or s[i]=='E' or s[i]=='i' or s[i]=='I' or s[i]
=='o' or s[i]=='O' or s[i]=='u' or s[i]=='U'):
c+=1
print ('The number of vowels in the sentence is' , c)
Output:
Enter a sentence: amazing day in alaska
The number of vowels in the sentence is 8
The number of vowels in the sentence is 8
The number of vowels in the sentence is 8
• The following program uses membership operators to see if
an entered substring is in a string:
checkstr.py
m=input("Enter a string: ")
n=input("Enter a substring: ")
if n in m:
print (n, "is found in the string", m)
else:
print (n,"does not exist in the string", m)
Output:
Enter a string: education
Enter a substring: cat
cat is found in the string education
Enter a string: education
Enter a substring: cari
cari does not exist in the string education
• The following program not only informs if a substring is found in a string or not but
also displays where the substring appears in the given string if it is found.
searchstr1.py
p=input("Enter a string: ")
print ("Entered String is ", p)
q=input("Enter the substring to search: ")
r=p.find(q)
if r==-1:
print (q, "not found in", p)
else:
print (q, "found in", p, "at location", r+1)
Output:
Enter a string: katherine
Entered String is katherine
Enter the substring to search: her
her found in katherine at location 4
• This program accepts a string and a substring from the user and uses the count()
method to count the occurrences of the substring in the given string. The count is
then displayed.
searchstr2.py
p=input("Enter a string: ")
print ("Entered String is", p)
q=input("Enter the substring to search: ")
r=p.count(q)
if r==0:
print (q, "not found in", p)
else:
print (q, "occurs in", p, r, "times")
Output:
Enter a string: alabalabalab
Entered String is alabalabalab
Enter the substring to search: la
la occurs in alabalabalab 3 times
• Methods to see if a string begins or ends with a given
prefix or suffix
• startswith(prefix, [start], [end])—Returns true if
the string starts with the specified prefix, otherwise
returns false. The prefix can be a single string or a
sequence of individual strings.
• endswith(suffix, [start], [end])—Returns true if the
string ends with the specified suffix; otherwise false is
returned. The suffix can be a single string or a
sequence of individual strings.
• Example:
stringfunc2.py
s=input("Enter a sentence: ")
print ('The original sentence is:', s)
if s.startswith('It'):
print('The entered sentence begins with the word It' )
if s.startswith('It', 0, 2):
print('The entered sentence begins with the word It' )
if s.endswith('today'):
print('The entered sentence ends with the word today' )
if s.endswith('today', 10, 15):
print('The entered sentence ends with the word today' )
Output:
Enter a sentence: It is hot today
The original sentence is: It is hot today
The entered sentence begins with the word It
The entered sentence begins with the word It
The entered sentence ends with the word today
The entered sentence ends with the word today
Arrays
• Numerical arrays are used for storing
numerical data. Since they don’t have NULL
characters, numerical arrays are not
terminated by NULL characters as with strings,
but the index concept still applies to them for
accessing their elements.
• The arrays are of two types, one- and two-
dimensional arrays.
One-Dimensional Arrays
• Consider a numerical array, p, which has five
numerical values: 8, 3,1, 6, and 2. These
values will be represented by the structure
shown
• Example
numericarr.py
p= [ 0 for i in range(5) ]
print ("Enter five numbers")
for i in range(5):
p[i]= int(input())
print ("Numbers entered in the array are", p)
print ("Numbers entered in the array are")
for n in p:
print (n)
Output:
Enter five numbers
8
3
1
6
2
Numbers entered in the array are [8, 3, 1, 6, 2]
Numbers entered in the array are
8
3
1
6
2
Two-Dimensional Arrays
• Two-dimensional arrays are divided into rows
and columns.
• The indices of row and column begin at value
0.
• To access each element of the array, you have
to specify two indices; one represents the row,
and the other represents the column.
• Example matrix1.py
table= [ [ 0 for i in range(3) ] for j in range(3) ]
print ("Enter values for a matrix of order 3 x 3")
for d1 in range(3):
for d2 in range(3):
table[d1][d2]= int(input())
print ("Elements of the matrix are", table)
print ("Elements of the matrix are")
for row in table:
print (row)
s=0
for row in table:
for n in row:
s+=n
print ("The sum of elements in matrix is",s)
Output:
Enter values for a matrix of order 3 x 3
1
2
3
4
5
6
7
8
9
Elements of the matrix are [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Elements of the matrix are
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
The sum of elements in matrix is 45
Lists
• A list is a collection of elements, which might
include other lists.
• Lists begin and end with a square bracket, and the
elements inside are separated with commas.
["John", "Kelly", 1, 2, [Sugar, Butter, 10]]
Output:
John
Paula
Finding the Length of the List
• To find the length of a list, you use the len() function, which
returns the length as an index location of the last element
plus one.
list2.py
names=['John', 'Kelly', 'Caroline',
'Paula']
for i in range(0,len(names)):
print (names[i])
Output:
John
Kelly
Caroline
Paula
• The in operator with an if statement can be
used to search for an element in the list.
list4.py
names=['John', 'Kelly', 'Caroline', 'Paula']
n=input("Enter a name: ")
if n in names:
print ("Entered name is present in the list")
else:
print ("Sorry the entered name is not in the list")
Output:
Enter a name: Susan
Sorry the entered name is not in the list
Enter a name: Caroline
Entered name is present in the list
List Slicing
• You can slice a list into parts to get desired
elements.
• To slice a list, you specify the index locations from
which you want to extract elements.
• Syntax:
list[first_index:following_index]
• This returns the elements from first_index to
the index before following_ index is returned.
• Example:
tmplist=['John', 'Kelly', 10, 'Caroline', 15, 'Steve',
'Katheline']
print ("The original list is", tmplist)
print ("The first four elements in the list are:", tmplist[0:4])
print ("The number of elements in the list are", len(tmplist))
m=input ("Enter a name to add to the list ")
tmplist.append(m)
print ("The elements in the list now are", tmplist)
n=int(input ("Enter the element number to delete "))
del tmplist[n-1]
print ("The elements in the list now are", tmplist)
print ("The elements in the list can also be displayed as shown:")
for i in range(0, len(tmplist)):
print (tmplist[i])
Tuples
• Tuples are a type of sequence, like strings.
• But unlike strings, which can contain only
characters, tuples can contain elements of any
type.
• A tuple is an immutable object that cannot be
changed once it is created.
• As with every sequence, tuple indices are zero
based; the first element is at index 0, and the last
element is at index -1.
• Example:
tup1.py
names=('John', 'Kelly', 'Caroline', 'Steve', 'Katheline')
print ("The names in the tuple are:", names)
print ("The first name in the tuple is", names[0])
print ("The last name in the tuple is", names[len(names)-1])
print ("The names in the tuple are")
for n in names:
print (n)
Output:
The names in the tuple are: ('John', 'Kelly', 'Caroline', 'Steve',
'Katheline')
The first name in the tuple is John
The last name in the tuple is Katheline
The names in the tuple are
John
Kelly
Caroline
Steve
Katheline
• Example:
tup2.py
names=('John', 'Kelly', 'Caroline', 'Steve', 'Katheline')
n=input("Enter the name to search: ")
if n in names:
print ("The name", n, "is present in the tuple")
else:
print ("The name", n, "does not exist in the tuple")
countries=('U.S.', 'U.K', 'India')
names+=countries
print ("The tuples are concatenated. The concatenated tuple is", names)
Output:
Enter the name to search: Beth
The name Beth does not exist in the tuple
The tuples are concatenated. The concatenated tuple is ('John',
'Kelly', 'Caroline',
'Steve', 'Katheline', 'U.S.', 'U.K', 'India')
Dictionary
• A dictionary is a combination of key/value
pairs in which every key has to be unique.
• Key/value pairs are separated by a colon, and
the pairs are separated by commas.
• The key/value pairs are enclosed in a curly
brackets.
• Syntax:
d = {key1 : value1, key2 : value2 }
• Dictionaries are mutable, which means a
dictionary can be modified, and you don’t
have to create a copy of it to modify it.
• Dictionary keys are case sensitive and
immutable because Python associates them
with a unique number called a hash.
• Also, dictionary keys can be of mixed data
types: strings, integers, and others.
• The following program demonstrates how to fetch a value
from the dictionary by supplying a key.
dict1.py
countrycap={'U.S.' : 'Washington D.C.', 'U.K.' : 'London', 'India' : 'New Delhi', }
n=input('Enter country: ')
if n in countrycap:
print ('The capital of', n , 'is', countrycap[n])
else:
print ('Sorry the country', n, 'does not exist in our dictionary')
countrycap['Australia']='Sweden'
print ('The dictionary after adding a country:')
for country, capital in countrycap.items():
print ('Capital of', country, 'is' , capital)
m=input('Enter the country to delete:')
del countrycap[m]
print ('The dictionary after deleting a country:')
for country, capital in countrycap.items():
print ('Capital of', country, 'is' , capital)
• The following program demonstrates the use of items(),
keys(), values(), and get() methods of the dictionary.
dictexample.py
student1={'John' : 60, 'Kelly' : 70, 'Caroline' : 80}
student2=dict([('David', 90), ('John',55)])
print ('The items in dictionary student1 are:', student1.items())
print ('The keys in student1 dictionary are:', student1.keys())
print ('The values in student1 dictionary are:', student1.values())
student1.update(student2)
print ('The items in dictionary student1 after merging with student2
dictionary are:',
student1.items())
n=input('Enter name whose marks you want to see: ')
if n in student1:
print ('The marks of', n , 'are' , student1.get(n))
else:
print ('Sorry the name', n, 'does not exist in student1 dictionary')
Sets
• A set is a collection of certain values.
• You can perform a number of set operations,
including union (|), intersection (&), difference
(-), and symmetric difference (^).
Union (|)
• In a union operation, an element appears in the
union if it exists in one set or the other.
• For example, consider the two sets S1 and S2 with
the following elements:
S1=set([3,5,6,10,11,100])
S2=set([1,3,5,6,11,15])
set([3, 5, 6, 11])
Difference (-)
• In a difference operation, all the elements that
are in the left set but not in the right set will
appear in the difference operation.
• S1-S2 will display the difference as :
set([10, 100])
• Example:
setexample.py
S1=set([3,5,6,10,11,100])
S2=set([1,3,5,6,11,15])
print ('Length of set S1 is:', len(S1))
print ('Maximum value in set S1 is:' , max(S1))
print ('Minimum value in set S2 is:' , min(S2))
print ('Sum of items in set S1 is:', sum(S1))
print ('Applying any() to set S1 results into:', any(S1))
print ('Union of the two sets is:', S1 | S2)
print ('Intersection of the two sets is:', S1 & S2)
print ('Difference of S1-S2 is:' , S1 - S2)
print ('Difference of S2-S1 is:' , S2 - S1)
S1.add(0)
print ('The items in set S1 after adding an item are:' , sorted(S1))
print ('As set S1 now has a value 0, so all() will result into:', all(S1))
S1.update(S2)
print ('The items in set S1 after merging set S2 are:' , sorted(S1))