Previous | Tutorial index | Next

Tutorial 1: An Introduction to Sequences in Python

Learning Objective

Explain sequences and perform common operations on them.

Overview

This foundational tutorial introduces the concept of a sequence in Python. You will learn what defines a sequence, the common operations that all sequences support, and which built‑in data types belong to this category. By the end, you will be comfortable working with strings, lists, and tuples using indexing, slicing, concatenation, repetition, and membership tests.

1. What Is a Sequence?

In Python, a sequence is an ordered collection of items. The order matters: each element occupies a fixed position, and you can access any element by its index (position number). The index starts at 0 for the first element, 1 for the second, and so on.

Key Characteristics of Sequences

Note: Not all ordered collections are sequences (e.g., a dict preserves insertion order from Python 3.7+, but it is a mapping, not a sequence, because it uses keys instead of integer indices). Sequences are a specific category in Python’s data model.

Example

my_string = "Hello" # a sequence of characters my_list = [10, 20, 30] # a sequence of integers my_tuple = (1, 2, 3) # a sequence of integers

All three are sequences. They can hold any data type (strings hold characters, lists and tuples can hold mixed types).

2. Common Sequence Operations

All sequences support a set of standard operations. Let’s explore each one with examples.

2.1 Indexing

Access an element by its position. The first index is 0, the last is len(sequence) - 1.

s = "Python" print(s[0]) # 'P' print(s[3]) # 'h' lst = [10, 20, 30, 40] print(lst[2]) # 30

Negative indexing counts from the end:

print(s[-1]) # 'n' print(lst[-2]) # 30

2.2 Slicing

Extract a sub‑sequence (a copy of a portion) using the syntax [start:stop:step].

s = "Hello, World!" print(s[0:5]) # 'Hello' (indices 0,1,2,3,4) print(s[7:]) # 'World!' (from index 7 to end) print(s[:5]) # 'Hello' (from start to index 4) print(s[::2]) # 'Hlo ol!' (every second character) lst = [10, 20, 30, 40, 50] print(lst[1:4]) # [20, 30, 40] (indices 1,2,3) print(lst[-3:-1]) # [30, 40] (negative indices work too) print(lst[::-1]) # [50, 40, 30, 20, 10] (reverse the list)

Important: Slicing always creates a new sequence object (a copy). For mutable sequences (like lists), modifying the slice does not affect the original.

2.3 Concatenation (+)

Combine two sequences of the same type to form a new sequence.

str1 = "Hello" str2 = "World" print(str1 + " " + str2) # 'Hello World' list1 = [1, 2] list2 = [3, 4] print(list1 + list2) # [1, 2, 3, 4] tuple1 = (5, 6) tuple2 = (7, 8) print(tuple1 + tuple2) # (5, 6, 7, 8)

You can only concatenate sequences of the same type (e.g., list + list works, but list + tuple raises a TypeError).

2.4 Repetition (*)

Repeat a sequence a given number of times.

print("Ha" * 3) # 'HaHaHa' print([0] * 5) # [0, 0, 0, 0, 0] print((1, 2) * 2) # (1, 2, 1, 2)

2.5 Membership Testing (in, not in)

Check whether an item exists in a sequence.

s = "Python" print('y' in s) # True print('x' in s) # False print('x' not in s) # True lst = [10, 20, 30] print(20 in lst) # True print(25 in lst) # False

2.6 Length (len())

Get the number of elements.

print(len("Hello")) # 5 print(len([1, 2, 3])) # 3

2.7 Minimum and Maximum (min(), max())

Find the smallest or largest element (works for comparable elements, e.g., numbers or strings).

print(min([5, 2, 9, 1])) # 1 print(max("abc")) # 'c' (lexicographically)

2.8 .index() and .count()

lst = [10, 20, 30, 20, 40] print(lst.index(20)) # 1 print(lst.count(20)) # 2

Note: .index() and .count() are methods of sequences, but they are widely available for lists, tuples, and strings.

3. Built‑in Sequence Types

Python has three primary built‑in sequence types:

Type Example Mutable? Homogeneous? Notes
str "Hello" No Characters only Immutable; characters are single‑character strings.
list [1, 2, 3] Yes Any types (mixed allowed) Most flexible, used for collections that change.
tuple (1, 2, 3) No Any types (mixed allowed) Immutable, often used for fixed data (e.g., coordinates).

3.1 Strings

s = "hello" # s[0] = 'H' # TypeError: 'str' object does not support item assignment s = "H" + s[1:] # valid: creates a new string

3.2 Lists

lst = [1, 2, 3] lst[0] = 99 # now [99, 2, 3] lst.append(4) # [99, 2, 3, 4]

3.3 Tuples

t = (1, 2, 3) # t[0] = 99 # TypeError: 'tuple' object does not support item assignment

Tuples are often used for heterogeneous data (e.g., (name, age, city)) where the meaning of each position is fixed.

3.4 Other Sequence Types

Python also provides range, bytes, and bytearray as sequences, but they are less common in introductory contexts. range is a sequence of numbers (immutable) often used in loops.

r = range(5) # 0,1,2,3,4 print(r[2]) # 2 print(list(r)) # [0,1,2,3,4]

4. Important Nuances

4.1 Slicing with Step

You can use a step value to skip elements or reverse the sequence.

s = "abcdefg" print(s[1:6:2]) # 'bdf' (indices 1,3,5) print(s[::-1]) # 'gfedcba' (reverse)

Negative step with positive start/stop: the slice goes backwards.

4.2 Nested Sequences

Sequences can contain other sequences (lists within lists, tuples within lists, etc.).

matrix = [[1, 2], [3, 4]] print(matrix[0][1]) # 2

Accessing nested elements uses repeated indexing.

4.3 Mutability and Shared References

When you slice a mutable sequence, you get a shallow copy – the new sequence contains references to the same objects. If those objects are mutable, changes inside them may affect both sequences.

a = [[1, 2], [3, 4]] b = a[:] # shallow copy b[0][0] = 99 print(a) # [[99, 2], [3, 4]] -- affected!

For immutable items (numbers, strings, tuples), this is usually not an issue.

5. Why Are Sequences Useful?

📝 Quiz – Check Your Understanding

  1. Which of the following are sequences in Python? (Select all that apply)

    Answer`list`, `str`, `tuple`
  2. What is the output of the following code?

    s = "Python" print(s[-2])
    Answer(C) `o` (negative indexing: -1 = 'n', -2 = 'o')
  3. True or False: Slicing a list always creates a new list object.

    AnswerTrue
  4. What does [1, 2, 3] + [4, 5] evaluate to?

    Answer(A) `[1, 2, 3, 4, 5]`
  5. How can you reverse the tuple t = (10, 20, 30, 40) using slicing?
    Write the expression.

    Answer`t[::-1]`
  6. What is the result of len("Hello, World!")?

    Answer13 (spaces and punctuation count)
  7. True or False: You can change the second element of a tuple like t = (1, 2, 3) by assigning t[1] = 99.

    AnswerFalse (tuples are immutable)
  8. Which method would you use to find the number of times 'a' appears in a string?

    Answer(C) `count()`
  9. Given lst = [10, 20, 30, 40, 50], what is lst[1:4:2]?

    Answer`[20, 40]` (start=1, stop=4 exclusive, step=2 → indices 1 and 3)
  10. Can you concatenate a list and a tuple?

    AnswerNo (you cannot concatenate different sequence types)

💻 Exercises – Practice Makes Perfect

Exercise 1: Indexing and Slicing
Given the string s = "Data Science", write Python expressions to:

Sample Solution ```python s = "Data Science" print(s[5]) # 'S' print(s[5:8]) # 'Sci' print(s[2:-1]) # 'ta Scienc' (from index 2 to second-last inclusive) print(s[::-1]) # 'ecneicS ataD' ```

Exercise 2: Concatenation and Repetition

Sample Solution ```python A = [1, 2, 3] B = [4, 5] print(A + B) # [1, 2, 3, 4, 5]

t = (0,) * 10 print(t) # (0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

print("Na" * 4 + " Batman!") # "NaNaNaNa Batman!"

</details> **Exercise 3: Membership and Length** - Write a condition that checks if `'e'` is present in the string `"Hello"`. - Write a condition that checks if `5` is **not** present in the list `[1, 2, 3, 4]`. - Find the length of the tuple `("apple", "banana", "cherry")`. <details><summary>Sample Solution</summary> ```python print('e' in "Hello") # True print(5 not in [1, 2, 3, 4]) # True print(len(("apple", "banana", "cherry"))) # 3

Exercise 4: Using .index() and .count()

Sample Solution ```python text = "abracadabra" print(text.index('a')) # 0 print(text.rindex('a')) # 10 (or use text[::-1].index('a') etc.) print(text.count('r')) # 2 ```

Exercise 5: Nested Sequences

Sample Solution ```python matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(matrix[1][1]) # 5 print(matrix[1]) # [4, 5, 6] print(matrix[0][-1]) # 3 ```

🏠 Homework – Deeper Thinking

Short Answer Questions

1. Sequence Function
Write a function called reverse_sequence(seq) that takes a sequence (string, list, or tuple) and returns a new sequence of the same type with the elements reversed without using the [::-1] trick or the reversed() function. Use a loop to build the reversed sequence.

Sample Answer ```python def reverse_sequence(seq): result = [] for i in range(len(seq)-1, -1, -1): result.append(seq[i]) if isinstance(seq, str): return ''.join(result) elif isinstance(seq, tuple): return tuple(result) else: return result ```

2. Palindrome Checker
A palindrome is a word, phrase, or sequence that reads the same forward and backward (ignoring case and spaces). Write a function is_palindrome(s) that takes a string s and returns True if it is a palindrome, False otherwise. Use sequence operations to check. For example:

Sample Answer ```python def is_palindrome(s): # Remove spaces and convert to lower case s = s.replace(" ", "").lower() return s == s[::-1] ```

3. List Manipulation
Write a program that:

  1. Creates a list of the first 10 even numbers (i.e., [2, 4, 6, ..., 20]).
  2. Replaces all multiples of 4 with the string "FOUR".
  3. Removes the last two elements.
  4. Inserts 100 at the beginning.
  5. Prints the final list.
Sample Answer ```python lst = [i for i in range(2, 21, 2)] # [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] for i, val in enumerate(lst): if val % 4 == 0: lst[i] = "FOUR" lst = lst[:-2] # remove last two lst.insert(0, 100) print(lst) # [100, 2, 'FOUR', 6, 'FOUR', 10, 'FOUR', 14] ```

4. Tuple Unpacking and Slicing
Given a tuple data = (10, 20, 30, 40, 50, 60):

Sample Answer ```python data = (10, 20, 30, 40, 50, 60) selected = data[::2] # (10, 30, 50) a, b, c = selected print(a, b, c) # 10 30 50 print(a + b + c) # 90 ```

Essay Questions

5. Sequence Comparison
Explain the difference between the following two operations:

a = [1, 2, 3] b = a c = a[:]
Sample Answer `b` is a reference to the same list as `a`, so `b` and `a` point to the same object in memory. `c` is a new list (a shallow copy) containing the same elements as `a` at the time of copying. When you change `a[0] = 99`, `b` will also reflect that change because it references the same list, but `c` remains unchanged because it is a separate copy. A shallow copy creates a new container but does not recursively copy nested objects; for immutable elements (like integers), this is fine. A deep copy (using `copy.deepcopy`) would recursively copy all nested structures.

Homework Hints

Summary

In this tutorial, you have learned:

Next Steps: In the next tutorial, we will dive deeper into lists – their methods, comprehensions, and common patterns. Stay tuned!

Happy coding!

Previous | Tutorial index | Next