You are on page 1of 12

Sequences 2

Learning Objectives 2
Strings and Lists 2
Strings 2
Lists 3
Tuples 3
Index Operator: Working with the Characters of a String 3
Index Operator: Accessing Elements of a List or Tuple 4
Check your understanding 5
Length 5
Check your understanding 6
The Slice Operator 7
List Slices 7
Tuple Slices 8
Check you understanding 8
Concatenation and Repetition 9
Check your understanding 9
Count and index 9
Count 9
Index 10
Check your understanding 10
Splitting and Joining Strings 11
Split 11
Join 11
Check your understanding 12
Sequences
In the real world most of the data that we care about is in the form of sequence or collection. For
example, the list of colleges in Palawan State University or a list of your enrolled subjects in the
current semester.

Python provides features to work with lists of all kinds of objects (numbers, words, etc.). The
character string is a sequence of individual letters.

In this module, you will use the different operations that can be performed on sequences, such
as picking out individual elements or subsequences (called slices) or computing their length. You
will also use different functions dedicated to strings. In addition, you will also find out the difference
between strings and lists.

There are different code snippets available in this module, try to run these in Google Colaboratory
to see the output. Practice by tweaking your code and predicting the output.

Notebook is provided for your answers in Trys and Check your understanding.

Learning Objectives
● Use different types of operations can be performed on strings, lists, and tuples.
● Distinguish between different uses of square brackets ([ ]) in Python.
● Predict the output of split and join operations.
● Read and write expressions that use slices.
● Read and write expressions that use concatenation and repetition.

Strings and Lists

Strings
A string is simply some characters inside quotes. For example, “Hello, world!”, ‘Palawan State
University’. Strings can be defined as a sequential collection of characters; individual characters
that make up a string are in particular order from left to right.

String that contains no characters is called an empty string. It is still considered to be a string and
represented by two single or two double quotes with nothing in between (‘’ or “”).
Lists
A list is a sequential collection of data values, each value in a list is called elements. Each element
in a list is identified by an index. Lists and Strings are similar, they are both collections of
characters, but the elements of a list can have different types (int, float, string, etc.) for one list.

To create a new list, enclose the elements in square brackets.


[1, 2, 3, 4]
["banana", "apple", "mango"]

The list doesn't have to be the same type. For example,


["hello", 2.0, 5, [10, 20]]

01 Try
- Assign a list of your current enrolled courses in variable enrolled.

Tuples
A tuple is like a list, it can be a sequence of items of any type. But instead of using square brackets,
tuples are represented using parenthesis.

ict1 = ("ICT1", "Computer Fundamentals and Programming", 2, "Laboratory",


"Wed 8:00-11:00", "NIT 3")

The difference between lists and tuples is that a tuple is immutable, meaning its content can’t be
changed after the tuple is created.

Index Operator: Working with the Characters of a String


Python uses square brackets to enclose the index to select a single character from a string.
The characters in a string are accessed by their position or index value. For example, “Palawan”
has seven characters and it is indexed left to right from position 0 to position 6.

0 1 2 3 4 5 6

P a l a w a n

-7 -6 -5 -4 -3 -2 -1

You can also use negative numbers as position or index value where -1 is the rightmost index
and so on.
school = "Palawan State University"
m = school[2]
print(m)

lastchar = school[-1]
print(lastchar)

The expression school[2] selects the character at index 2 from the value of variable school. The
letter at index zero of “Palawan State University” is P. So at position [2] we have letter l.

02 Try
- Given the statement school = "Palawan State University" , get the letter ‘S’ and
assign it to a variable letter.

Index Operator: Accessing Elements of a List or Tuple

Same as in the string, you will use square brackets to access the elements of list or tuple.
Remember that indices start at 0, any integer expression can be used as an index. Negative
index value will locate items from the right.

Try to predict what will be printed out by the following code, then run the code in Google
Colaboratory to check your prediction.

numbers = [17, 123, 87, 34, 66, 8398, 44]


print(numbers[2])
print(numbers[9-8])
print(numbers[-2])

03 Try
- Using square brackets to access values, display the sum of elements whose values are
87, 34, and 44.

prices = (1.99, 2.00, 5.50, 20.95, 100.98)


print(prices[0])
print(prices[-1])
print(prices[3-5])
01 Check your understanding
1. What is printed by the following statements?
s = "python rocks"
print(s[3])

2. What is printed by the following statements?


s = "python rocks"
print(s[2] + s[-4])

3. What is printed by the following statements?


alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False]
print(alist[5])

4. Assign the value of the 34th element of lst to the variable output.
lst = ["hi", "morning", "dog", "506", "caterpillar", "balloons", 106, "yo-
yo", "python", "moon", "water", "sleepy", "daffy", 45, "donald",
"whiteboard", "glasses", "markers", "couches", "butterfly", "100",
"magazine", "door", "picture", "window", ["Olympics", "handle"], "chair",
"pages", "readings", "burger", "juggle", "craft", ["store", "poster",
"board"], "laptop", "computer", "plates", "hotdog", "salad", "backpack",
"zipper", "ring", "watch", "finger", "bags", "boxes", "pods", "peas",
"apples", "horse", "guinea pig", "bowl", "EECS"]

5. Assign the value of the last character of lst to the variable output. Do this so that the
length of lst doesn’t matter.
lst = "Every chess or checkers game begins from the same position and has a
finite number of moves that can be played. While the number of possible
scenarios and moves is quite large, it is still possible for computers to
calculate that number and even be programmed to respond well against a
human player..."

Length
The len function returns the number of characters in a string.

fruit = "Banana"
print(len(fruit))
To get the last letter of a string using the len function in the expression.

fruit = "Banana"
sz = len(fruit)
lastch = fruit[sz-1]
print(lastch)

Using sz as an index will cause runtime error because there is no letter at index position 6 in
“Banana”, since indexing starts counting at zero. To get the last character, you have to subtract
1 from the length.

Typically, you can combine lines 2 and 3 to a single line statement.

lastch = fruit[len(fruit)-1]

You can also use the len function to access the middle character of the string.
fruit = "grape"
midchar = fruit[len(fruit)//2]

When the len function is used in a list it will return the number of items in the list.

alist = ["hello", 2.0, 5]


print(len(alist))
print(len(alist[0]))

02 Check your understanding


1. What is printed by the following statements?
s = "python rocks"
print(len(s))

2. What is printed by the following statements?


alist = [3, 67, "cat", 3.14, False]
print(len(alist))

3. Assign the number of elements in lst to the variable output.


lst = ["hi", "morning", "dog", "506", "caterpillar", "balloons", 106,
"yo-yo", "python", "moon", "water", "sleepy", "daffy", 45, "donald",
"whiteboard", "glasses", "markers", "couches", "butterfly", "100",
"magazine", "door", "picture", "window", ["Olympics", "handle"],
"chair", "pages", "readings", "burger", "juggle", "craft", ["store",
"poster", "board"], "laptop", "computer", "plates", "hotdog",
"salad", "backpack", "zipper", "ring", "watch", "finger", "bags",
"boxes", "pods", "peas", "apples", "horse", "guinea pig", "bowl",
"EECS"]

The Slice Operator


A substring of a string is called a slice. Selecting a slice is similar to selecting a
character.

print(singers[0:5])
print(singers[7:11])
print(singers[17:21])

The slice operator [n:m] returns part of the string starting with a character at index n and
going up to but not including the character at index m.

If you omit the first index (n) before the colon, the slice starts at the beginning of the
string. If you omit the second index (m) the slice goes to the end of the string.

fruit = "banana"
print(fruit[:3])
print(fruit[3:])

List Slices
The slice operation used in a string will work on list elements too.

a_list = ['a', 'b', 'c', 'd', 'e', 'f']


print(a_list[1:3])
print(a_list[:4])
print(a_list[3:])
print(a_list[:])
Tuple Slices
You can’t modify the elements of a tuple, but you can make a variable reference a new tuple
holding different values.

julia = ("Julia", "Roberts", 1967, "Duplicity", 2009, "Actress", "Atlanta,


Georgia")
print(julia[2])
print(julia[2:6])

print(len(julia))

julia = julia[:3] + ("Eat Pray Love", 2010) + julia[5:]


print(julia)

03 Check you understanding

1. What is printed by the following statements?


s = "python rocks"
print(s[3:8])

2. What is printed by the following statements?


alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False]
print(alist[4:])

3. What is printed by the following statements?


L = [0.34, '6', 'SI106', 'Python', -2]
print(len(L[1:-1]))

4. Create a new list using the 9th through 12th elements (four items in all) of new_lst and
assign it to the variable sub_lst.
new_lst = ["computer", "luxurious", "basket", "crime", 0, 2.49, "institution",
"slice", "sun", ["water", "air", "fire", "earth"], "games", 2.7, "code",
"java", ["birthday", "celebration", 1817, "party", "cake", 5], "rain",
"thunderstorm", "top down"]
Concatenation and Repetition
The + operator concatenates the lists same as with the strings. The * operator repeats the items in a
list given the number of times.

Run the code below.

fruit = ["apple","orange","banana","cherry"]
print([1,2] + [3,4])
print(fruit+[6,7,8,9])

print([0] * 4)

When newlist is created by the statement newlist = fruit + numlist, it is a completely new list formed
by making copies of the items from fruit and numlist.

04 Check your understanding


1. What is printed by the following statements?
alist = [1,3,5]
blist = [2,4,6]
print(alist + blist)

2. What is printed by the following statements?


alist = [1,3,5]
print(alist * 3)

Count and index

Count

To use the count method, you need to provide one argument, which is what you want to count. This
method will return the number of times that the argument occurred in the string/list.

a = "I have had an apple on my desk before!"


print(a.count("e"))
print(a.count("ha"))

The statement print(a.count("e")) will return the number of occurrences of “e” in “I have had an
apple on my desk before!”.

z = ['atoms', 4, 'neutron', 6, 'proton', 4, 'electron', 4, 'electron', 'atoms']


print(z.count("4"))
print(z.count(4))
print(z.count("a"))
print(z.count("electron"))

Why do you think print(z.count("4")) and print(z.count("a")) returns 0? This is because


the list z only contains integer 4, there are no strings that are 4. And though some words contain “a”
like atoms, the program is looking for items in the list that are just the letter “a”.

Index
Like the count method, the index method requires one argument. For both strings and list, index
returns the leftmost index where the argument is found.

music = "Pull out your music and dancing can begin"


bio = ["Metatarsal", "Metatarsal", "Fibula", [], "Tibia", "Tibia", 43, "Femur",
"Occipital", "Metatarsal"]

print(music.index("m"))
print(music.index("your"))

print(bio.index("Metatarsal"))
print(bio.index([]))
print(bio.index(43))

The “Metatarsal” appears three times in the list bio and the statement
print(bio.index("Metatarsal")) returns 0. Why is that? Even though “Metatarsal” occurs
many times, the method will only return the location of one of them, that is the leftmost index.

An error will occur if the argument is not in the string or list. Try to run this example.
seasons = ["winter", "spring", "summer", "fall"]

print(seasons.index("autumn")) #Error!

05 Check your understanding


1. What will be stored in the variable ty below?
qu = "wow, welcome week!"
ty = qu.index("we")

2. What will be stored in the variable ty below?


qu = "wow, welcome week! Were you wanting to go?"
ty = qu.count("we")

3. What will be stored in the variable ht below?


rooms = ['bathroom', 'kitchen', 'living room', 'bedroom', 'closet', "foyer"]
ht = rooms.index("garden")

Splitting and Joining Strings

Split

The split method breaks a string into a list of words. Whitespaces is considered a word
boundary.

song = "The rain in Spain..."


wds = song.split()
print(wds)

You can use an optional argument, it is called delimiter. It is used to specify which characters to use
as word boundaries. The following example uses the string ‘ai’ as the delimiter.

song = "The rain in Spain..."


wds = song.split('ai')
print(wds)

Join
You choose the desired separator string (often called glue) and join the list with the glue between
each of the elements.

wds = ["red", "blue", "green"]


glue = ';'
s = glue.join(wds)
print(s)
print(wds)

print("***".join(wds))
print("".join(wds))
After the execution of the statement s = glue.join(wds) the value of s will be red;blue;green.
Every item in the list wds will be joined separated by ‘;’ which is the value of glue.

06 Check your understanding


1. Create a new list of the 6th through 13th elements of lst (eight items in all) and assign it
to the variable output.
lst = ["swimming", 2, "water bottle", 44, "lollipop", "shine", "marsh",
"winter", "donkey", "rain", ["Rio", "Beijing", "London"], [1,2,3], "gold",
"bronze", "silver", "mathematician", "scientist", "actor", "actress",
"win", "cell phone", "leg", "running", "horse", "socket", "plug",
["Phelps", "le Clos", "Lochte"], "drink", 22, "happyfeet", "penguins"]

2. Create a variable output and assign it to a list whose elements are the words in the string
str1.

str1 = "OH THE PLACES YOU'LL GO"

You might also like