Professional Documents
Culture Documents
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
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.
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.
The difference between lists and tuples is that a tuple is immutable, meaning its content can’t be
changed after the tuple is created.
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.
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.
03 Try
- Using square brackets to access values, display the sum of elements whose values are
87, 34, and 44.
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.
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.
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.
print(len(julia))
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.
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.
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.
The statement print(a.count("e")) will return the number of occurrences of “e” in “I have had an
apple on my desk before!”.
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.
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!
Split
The split method breaks a string into a list of words. Whitespaces is considered a word
boundary.
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.
Join
You choose the desired separator string (often called glue) and join the list with the glue between
each of the elements.
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.
2. Create a variable output and assign it to a list whose elements are the words in the string
str1.