Basics of Python 3: Sequence Objects(Harvard PH526 Using Python for Research)

Oolong Break
7 min readOct 17, 2022

--

This article is my notes from a HarvardX class, Using Python for Research, offered by edX.org.

Sequences

A sequence is a collection of objects ordered by their position. In Python, there are three basic sequences: lists, tuples, and range objects. Any sequence data type will support the common sequence operations. They would also each have their methods for performing specific operations. The objects in a sequence form a sequence, as the name indicates. Indexing of a sequence starts at 0. We can also count from a sequence’s right to left, giving it a negative index. The last object has an index of -1.

Slicing is a sequence operation. We can use S[0:2] as an example. 0 is the start position, and 2 is the stop position. Python slices stop before Python reaches the element at the stop location. In this example, Python will return a slice of objects in locations 0 and 1.

Lists

Lists are mutable sequences of objects of any type, typically used to store homogeneous items. If we compare a string and a list, strings are sequences of individual characters, whereas lists are sequences of any type of Python object. Another difference is that strings are immutable, whereas lists are mutable.

List examples

We can also use the plus sign to concatenate two lists containing the same type of objects.

List concatenation example

We can use the reserve method to reserve the element order in a list. List methods are in-place methods; they modify the original list.

list.reverse() example

The reverse method, once called, moves the first object last and the last object first. It then closes in using the rest of the objects moving to the center of the list.

The sort method sorts the content of the list.

list.sort() example

There is another function in Python called “sorted.” Unlike sort(), an in-place method, the sorted function constructs a new list using the objects in the list. The objects in the new list appear in sorted order.

sorted() method example

The generic sequence function len() will tell us how many objects the list contains.

len() example

Tuples

Tuples are immutable sequences typically used to store heterogeneous data. You can view tuples as single objects that consist of different parts. Tuples are useful when you want to return multiple objects from your Python function.

Tuple examples

This is how you pack a tuple:

Tuple packing example

We can also unpack a tuple:

Tuple unpacking

Tuples in for loops are extremely handy. We can go through a tuple of coordinates and unpack all of the elements using a for loop:

Tuple in for loops example

Note that we don’t have to have the parentheses around “x, y.”

If we want to create a tuple with only one element, we have to put a comma after the element:

Single element tuple example

Ranges

Ranges are immutable sequences of integers that are commonly used in for loops. To create a range, we put the stopping value in the parentheses:

Create range example

To see the objects in a range object, we can turn it into a list:

Turn range into a list example

We can also provide the starting point and define the step size in a range object:

Starting point and step size example

Range has the advantage of taking up less storage. To store a range object, Python only stores three numbers: the starting point, the stopping point, and the step size. This saves up a lot of storage space if you want to loop through a large data set.

Strings

Strings are immutable sequences of characters. Here are some common functions on strings:

String examples
String slicing example

We can test for memberships using strings:

String membership testing example

Strings have the quality of polymorphism, which means what an operator does depends on the type of objects it is being called on. For example, “adding” two strings together using a plus sign is possible and is known as concatenation.

String concatenation example

Strings can also be multiplied:

String multiplication

You can’t add a number to a string:

Add numbers to strings example

However, you can convert the number to a string using the str() function and add the two strings together:

Convert a number to a string and add it to another string

We can ask for help by typing a function and adding a question mark at the end.

Using Python built-in help

We can use the replace function like this:

String replace function example

Since strings are immutable, Python will only return a new string without modifying the old string. To keep this new string, we’ll have to assign it to a variable:

Assigning a new string to a variable

The split method takes a string and breaks it down to substrings. We’ll need to specify which character we would like to use for splitting the string:

String split example

We can also turn the characters into upper or lower cases using the respective methods:

Sets

Sets are unordered collections of distinct hashable objects. In practice, you can use sets for immutable objects like numbers and strings but not for mutable objects like lists and dictionaries. There are two types of sets: set and frozen set. The difference is that a frozen set is immutable once created. One of the key ideas about sets is that they can’t be indexed, so the objects don’t have locations. Another key feature is that the elements can never be duplicated. This means all the objects inside a set will always be unique or distinct. Python sets are especially useful for keeping track of distinct objects and doing set operations like unions, intersections, and set differences. Here are some set methods:

Set operation examples

We can use the pop method to remove one element from the set:

Set pop method example

Here is an example of using Python set to perform mathematical set differences:

Example of set differences

We can perform the set union operation as well. The shorthand operation for a set union in Python is a vertical line:

Set union example

We can take an intersection of two sets using the ampersand operation:

Set intersection example

Let’s use sets to count the number of unique letters in a word:

Set application example

Dictionaries

Dictionaries are mappings from key objects to value objects. Dictionaries consist of Key:Value pairs, where the keys must be immutable, and the values can be anything. Dictionaries themselves are mutable; we can modify the content once created. Dictionaries can be used for performing fast lookups on unordered data. Dictionaries are not sequences, so there is no order, which means when looping through a dictionary, the key:value pairs will be iterated over in arbitrary order. There are two ways to construct a dictionary object:

Dictionary construction

Here is how to perform a lookup in a dictionary:

Dictionary lookup example

We can change the value of key-value pair in a dictionary using one of the two methods:

Dictionary modify value example

You can use the dictionary method keys to find out all the keys in the dictionary and the value method to find out all of the values in the dictionary. Python returns an object with a special object type: a view object. They provide a dynamic view of the keys or values in the dictionary. As you update or modify your dictionary, the views will also change.

Dictionary view object example

Finally, we can test for membership for the key objects in a dictionary:

Dictionary membership test example

--

--

Oolong Break
Oolong Break

Written by Oolong Break

Eat, Learn, Love. YouTube Channel: Oolong Break

No responses yet