Sequences and Loops

Strings as a Sequence

Sequences are an abstract type in Python that represent ordered collection of elements: e.g., strings, lists, range objects, etc.

Today we will focus on strings which are an ordered sequence of individual characters (also of type str)

We can access each character of a string using indices in Python.

Accessing elements of a sequence using [] operator

Length of a Sequence

len() function. Python has a built-in len() function that computes the length of a sequence such as a string (or a list, which we will see in next lecture).

Thus, a string word has (positive) indices 0, 1, 2, ..., len(word)-1.

Negative Indexing

Python also allows for negative indices, staring at -1 which is a handy way to refer to the last element of a non-empty sequence (regardless of its length).

Thus, a string word has (negative) indices -1, -2, ..., -len(word).

Defining is_vowel function

Let us write a function is_vowel function that takes a character as input and returns whether or not it is a vowel.

We can check if a letter is a vowel by comparing it against every possible upper or lower case vowel. We will learn a better way to write this function soon, but this works for now!

Towards Iteration: Counting Vowels

Problem. Write a function count_vowels that takes a string word as input, counts and returns the number of vowels in the string.

def count_vowels(word):
     '''Returns number of vowels in the word'''
     pass

Expected behavior:

>>> count_vowels('Williamstown')
4
>>> count_vowels('Ephelia')
4
>>> count_vowels('rythm')
0

Re-using functions. Since we have defined is_vowel, we can use it to test individual characters of the string, rather than starting from scratch.

What do we need to do to solve this problem?

Attempts using Conditionals

Suppose we manually check each character of the string and update a counter if it is a vowel.

Question. How good is this approach? Will it work for any word?

Takeaway. Downsides of this approach are many:

Iteration over Sequences: for loops

We can "iterate" over the elements of a sequence using a for loop. A loop is a mechanism to repeat the same operations for an entire sequence.

Syntax of for loop

for var in seq:
     do something

var above is called the loop variable of the for loop. It takes on the value of each of the elements of the sequence one by one.

Putting it Together: countVowels

Now, we are ready to implement our function that takes a string as input and returns the number of vowels in it.

Pythonic looping. Notice that the for loop does not need to know the length of the sequence ahead of time. This is a bit of Python magic (in other languages such as Java, you do need to know the length of the sequence you are iterating over). In Python, the for loop automatically finishes after the sequence runs out of elements, e.g., word runs out of characters, even though we have not computed the length manually.

Tracing the loop. To observe how the variables char and count change state as the loop proceeds, we can add print statements.

Summary. As you can see, the loop variable char takes the value of every character in the string one by one until the last character. Inside the loop, we check if char is a vowel and if so we increment the counter.

Exercise: vowel_seq

Define a function vowe_seq that takes a string word as input and returns a string containing all the vowels in word in the same order as they appear.

Example function calls:

>>> vowel_seq("Chicago")
'iao'
>>> vowel_seq("protein")
'oei'
>>> vowel_seq("rhythm")
''

Lists

A New Sequence: Lists

Recall that sequences are an abstract type in Python that represent ordered collections of elements.

In the last lecture we focused on strings. Today we will discuss lists.

Unlike strings, which are a homogenous sequence of characters, lists can be a collection of heterogenous objects.

Sequence Operators

Here are several operators that apply to any sequence, including lists and strings.

The in operator tests membership and returns True if and only if an element is in a sequence. On the other hand, the not in operator returns True if and only if a given element is not in the sequence.

Note that it is preferable and more readable to say if el not in seq compared to the (logically equivalent) if not el in seq.

Slicing Sequences

Python allows us to extract subsequences of a sequence using the slicing operator [:].

For example, suppose we want to extract the substring Williams from Williamstown. We can use the starting and ending indices of the substring and the slicing operator [:].

Slicing Sequences with Optional Step

The slicing operator [:] optionally takes a third step parameter that determines in what direction to traverse, and whether to skip any elements while traversing and creating the subsequence.

By default the step is set to +1 (which means move left to right in increments of one).

We can pass other step parameters to obtain new sliced sequences; see examples below.

Nifty Way to Reverse Sequences

The optional parameter does not come up too often, but does provide a nifty way to reverse sequences.

For example, to reverse a string, we can set the optional step parameter to -1.

Testing membership: in operator

The in operator in Python returns True/False value and is used to test if a given sequence is a subsequence of another sequence.

For example, we can use it to test if a string is a substring of another string (a substring is a contiguous sequence of characters within a string, e.g. Williams is a substring of Williamstown)