Previous | Tutorial index | Next
Explain sequences and perform common operations on them.
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.
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.
for loop).len().Note: Not all ordered collections are sequences (e.g., a
dictpreserves 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.
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).
All sequences support a set of standard operations. Let’s explore each one with examples.
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:
-1 = last element, -2 = second last, etc.print(s[-1]) # 'n'
print(lst[-2]) # 30
Extract a sub‑sequence (a copy of a portion) using the syntax [start:stop:step].
start – index where the slice begins (inclusive). Defaults to 0.stop – index where the slice ends (exclusive). Defaults to the length.step – the increment (optional). Defaults to 1.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.
+)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).
*)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)
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
len())Get the number of elements.
print(len("Hello")) # 5
print(len([1, 2, 3])) # 3
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)
.index() and .count().index(x) – returns the first index where x appears (raises ValueError if not found)..count(x) – returns the number of occurrences of x.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.
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). |
s = "hello"
# s[0] = 'H' # TypeError: 'str' object does not support item assignment
s = "H" + s[1:] # valid: creates a new string
[].lst = [1, 2, 3]
lst[0] = 99 # now [99, 2, 3]
lst.append(4) # [99, 2, 3, 4]
() (though commas define the tuple, parentheses are optional).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.
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]
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.
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.
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.
len, min, max) and methods work on all sequences.Which of the following are sequences in Python? (Select all that apply)
What is the output of the following code?
s = "Python"
print(s[-2])
PnohTrue or False: Slicing a list always creates a new list object.
What does [1, 2, 3] + [4, 5] evaluate to?
[1, 2, 3, 4, 5][5, 7, 8][1, 2, 3, [4, 5]]TypeErrorHow can you reverse the tuple t = (10, 20, 30, 40) using slicing?
Write the expression.
What is the result of len("Hello, World!")?
True or False: You can change the second element of a tuple like t = (1, 2, 3) by assigning t[1] = 99.
Which method would you use to find the number of times 'a' appears in a string?
find()index()count()search()Given lst = [10, 20, 30, 40, 50], what is lst[1:4:2]?
Can you concatenate a list and a tuple?
Exercise 1: Indexing and Slicing
Given the string s = "Data Science", write Python expressions to:
"Sci" using slicing.Exercise 2: Concatenation and Repetition
A = [1, 2, 3] and B = [4, 5]. Combine them into [1, 2, 3, 4, 5] using concatenation.t = (0,) and repeat it 10 times to get (0, 0, 0, 0, 0, 0, 0, 0, 0, 0)."Na" repeated 4 times, followed by " Batman!". What is the result?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()
text = "abracadabra", find the index of the first 'a' and the index of the last 'a'.'r' appears in text.Exercise 5: Nested Sequences
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]].
5.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.
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:
"radar" → True"hello" → False"A man a plan a canal Panama" → True3. List Manipulation
Write a program that:
[2, 4, 6, ..., 20])."FOUR".100 at the beginning.4. Tuple Unpacking and Slicing
Given a tuple data = (10, 20, 30, 40, 50, 60):
a, b, c.5. Sequence Comparison
Explain the difference between the following two operations:
a = [1, 2, 3]
b = a
c = a[:]
b and c?a[0] = 99, what happens to b and c? Why?''.join(reversed_list)).enumerate, and list methods.data[::2] gives (10,30,50), then unpack.b references the same list, c is a shallow copy; changing a affects b but not c.In this tutorial, you have learned:
.index(), .count().str, list, tuple, and their mutability differences.Next Steps: In the next tutorial, we will dive deeper into lists – their methods, comprehensions, and common patterns. Stay tuned!
Happy coding!