CS1010E Chap.3 Sequences and Iterables
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.
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
- 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.
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.
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.
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.