National University of Singapore · FACULTY OF COMPUTER SCIENCE

CS1010E Chap.3 Sequences and Iterables

- one subject, every graph, every model, every mark
8 Chapters4-page Bible
Our own words - no uploaded lecturer files
Updated for this semester
Chapter 3 of 6 · CS1010E

Sequences and Iterables

From single values to collections

The first weeks of CS1010E work with singleton values such as integers, floats and booleans. This chapter introduces values that contain other values. A tuple holds an ordered run of items inside round brackets, the items may be of different types, and once the tuple exists nothing inside it can be replaced.

A string is the same idea specialised to characters, and characters carry an order taken from the ASCII table, which is why strings can be compared with the usual relational operators.

Both kinds of sequence share one toolkit.

You can pick out a single element by its index, cut out a slice with start, stop and step, join two sequences with the plus operator, repeat one with the star operator, and ask whether a value is present with the in operator. Strings go further: in also detects a sub-string, not just a single character.

Immutability is a feature rather than a limitation.

Since a tuple or string can never change after it is built, the same expression applied to it always gives the same answer, and code that relies only on immutable values is easy to reason about. Trying to assign to an element raises a TypeError.

The second assignment leans on this directly: apart from character strings, every sequence must be written as a tuple, and lists, sets, dictionaries and sequence methods are not permitted.

Indexing and slicing as a skill

Every position has two names. Forward indices begin at 0 on the left, and backward indices begin at -1 on the right, so in a five-item tuple index 1 and index -4 point at the same element.

A slice stops just before its stop index. The most reliable habit is to settle the step before anything else: a positive step walks left to right, a negative step walks right to left, and the start must sit on the side where the walk begins.

Leaving start or stop blank means running to the end, so a full slice copies and a step of -1 reverses.

Iterables and the higher order tools

An iterable is anything that can supply its elements one at a time. Every sequence qualifies, and so do the lazy objects created by range, map, filter and generator expressions.

Those lazy objects produce nothing visible until something consumes them, typically a call to tuple, and once consumed they are empty. Map applies a function to every element, filter keeps the elements that satisfy a predicate, and reduce from functools folds the iterable into one value with a two-argument function, optionally starting from an initializer.

Because each of them takes a function as an argument they are higher order functions, and the lambda expression lets you write that argument inline. The course closes the topic by writing its own higher order functions, including ones that return a new function.

In this chapter

What this chapter covers

  • 01

    Tuples as immutable ordered sequences

  • 02

    Forward and backward indexing

  • 03

    Slicing with start, stop and step

  • 04

    Joining and repeating sequences with + and *

  • 05

    Strings, ASCII order and lexicographic comparison

  • 06

    Ranges and lazy iterables

  • 07

    Lambda expressions with map and filter

  • 08

    Reduction with reduce and an initializer

Worked example · free

Reading and writing slices on a tuple of multiples

Q [6 marks]. Let t = (3, 6, 9, 12, 15, 18, 21). (a) Write a readable expression for the last three values in reverse order and give its result. (b) Evaluate t[1:-1:2]. (c) Evaluate t[-2:-6:-1]. (d) Give a range expression that rebuilds t when wrapped in tuple. The step weighting shown here is an AskSia study allocation and is not a University marking scheme.
Figure 3.1.Figure 3.1. Strings and tuples sit inside the sequence box, so indexing and slicing work on them. Map, filter and generator objects are iterable only: they produce values on demand and are used up after one pass. Lists arrive in a later lecture as the mutable sequence. iterable: yields values one at a time sequence str tuple list index, slice, +, *, in, len mutable, later map, filter generator one pass, then empty
Figure 3.1. Strings and tuples sit inside the sequence box, so indexing and slicing work on them. Map, filter and generator objects are iterable only: they produce values on demand and are used up after one pass. Lists arrive in a later lecture as the mutable sequence.
  • 2Reverse first, then take the front: t[::-1] is (21, 18, 15, 12, 9, 6, 3), and its first three items give the answer.
  • 1For t[1:-1:2], start at index 1, stop before the last index, step forward by 2.
  • 2For t[-2:-6:-1], start at the second last item and walk left, stopping before index -6.
  • 1Match the pattern to range: start 3, step 3, stop just past 21.
(a) t[::-1][:3] gives (21, 18, 15). It is easier to read than the equivalent t[:-4:-1], because each step does one job: the first slice reverses and the second keeps three items. (b) t[1:-1:2] visits indices 1, 3 and 5, since index 6 is the excluded stop, so the result is (6, 12, 18). (c) t[-2:-6:-1] starts at index -2, holding 18, and walks left through -3, -4 and -5 before stopping just before -6, giving (18, 15, 12, 9). (d) tuple(range(3, 22, 3)) produces (3, 6, 9, 12, 15, 18, 21), because range excludes its stop value in exactly the way a slice excludes its stop index, so the stop must be any value above 21 and no higher than 24.
Sia tip — Write the slice end as one past the last index you want, and fix the sign of the step before choosing start and stop: t[2:5] gives (9, 12, 15) and stops at index 4.
Glossary

Key terms

Tuple
Stores an ordered, immutable sequence of values written in round brackets and separated by commas; a single item needs a trailing comma, as in (7,).
Sequence
Holds elements in a fixed order so each can be reached by an index; strings and tuples are the sequences used in this part of the course.
Iterable
Supplies its elements one at a time when asked. Every sequence is iterable, and so are lazy objects such as map and filter results.
Slice
Builds a new sequence from start, stop and step inside square brackets; the stop index is excluded and blank positions run to the end.
Negative Index
Counts positions from the right end, with -1 naming the last element and -n naming the first element of an n-item sequence.
Lambda Expression
Creates a small unnamed function inline, written as lambda parameters: expression, and gives back a function value that can be passed or called at once.
Higher Order Function
Takes a function as an argument or returns one as its result; map, filter and reduce are the standard examples.
Reduction
Folds an iterable into one value by applying a two-argument function from left to right, optionally beginning from an initializer.
Lexicographic Order
Compares strings character by character from the left using ASCII positions, so the first differing character decides and uppercase sorts before lowercase.
FAQ

Sequences and Iterables FAQ

Why does (5) not create a tuple in Python?

Round brackets on their own only group an expression, so (5) evaluates to the integer 5 and (5) * 2 gives 10. The comma is what makes a tuple: (5,) * 2 gives (5, 5). For an empty tuple, tuple() reads more clearly than a bare pair of brackets.

Why does sum of a map object return 0 the second time?

A map object generates its values lazily and hands each one out only once. The first sum drains it completely, so a second sum sees an empty iterable and returns 0. Convert the result with tuple if the values are needed more than once.

When should reduce be given an initializer?

Pass one whenever the iterable could be empty or the running result has a different type from the elements. Without it, reduce on an empty iterable raises a TypeError; with it, reduce simply returns the initializer, such as 0 for a sum or an empty tuple when building a tuple.

Why is 'Zebra' less than 'apple' in Python?

Strings compare one character at a time using ASCII positions, and every uppercase letter sits before every lowercase letter in that table. The first characters already differ, Z against a, and Z has the smaller code, so the comparison ends there and returns True.

How do I reverse only the last few items of a sequence?

Build the slice in two readable steps instead of one tangled one. Reverse the whole sequence with a step of -1, then take the first k items of the reversed result. This avoids negative starts and stops that are easy to get wrong under time pressure.

Study strategy

Exam move

Take one five-item tuple and one short string, write out both rows of indices by hand, then predict a dozen slices with positive and negative steps before checking each in IPython. After that, rewrite three small map, filter and reduce chains as generator expressions and confirm the outputs match.

Working through Sequences and Iterables in CS1010E? Sia is AskSia’s AI Computer Science tutor — ask any CS1010E Sequences and Iterables question and get a clear, step-by-step explanation grounded in how CS1010E is taught and assessed. Read this chapter free, then take your hardest questions to Sia.

A+Everything unlocked
Unlocks this Bible + all 21 of your National University of Singapore subjects - and 1,000+ Bibles across every Australian university.
Sia - your CS1010E tutor, unlimited, worked the way the exam marks it
The full 4-page Bible + practice bank with worked solutions
Chrome extension - sync your LMS so Sia knows your deadlines
Bilingual EN / Chinese on every Bible and every Sia answer
$0.99 Trial
30-day money-back · cancel in one tap · how it works