Data Structures & Collections: String, List, and Tuple
Python provides powerful built-in sequence data structures that store multiple items in a specific order. Every item in a sequence has an index (position):
- Positive Indexing: Starts from
0(left to right:0, 1, 2, ...). - Negative Indexing: Starts from
-1(right to left:-1, -2, -3, ...).
1. String (str) in Python
A String is an ordered, immutable sequence of Unicode characters enclosed within single quotes ('...'), double quotes ("..."), or triple quotes ('''...''').
Key Properties of Strings:
- Ordered: Characters maintain their insertion order and can be accessed via index.
- Immutable (Cannot be changed in-place): Once a string is created, you cannot modify a single character like
s[0] = 'J'.
String Slicing (string[start : stop : step]):
Extracts a substring starting at start up to stop - 1.
text = "PYTHON"
print(text[0]) # 'P' (First character)
print(text[-1]) # 'N' (Last character)
print(text[0:4]) # 'PYTH' (Index 0 to 3)
print(text[2:]) # 'THON' (From index 2 to end)
print(text[::-1]) # 'NOHTYP' (Reverses the string!)
Important Built-in String Methods:
| Method | Description | Example (s = " hello world ") |
|---|---|---|
s.upper() |
Converts all characters to uppercase | " HELLO WORLD " |
s.lower() |
Converts all characters to lowercase | " hello world " |
s.title() |
Capitalizes first letter of each word | " Hello World " |
s.strip() |
Removes leading and trailing spaces | "hello world" |
s.replace(old, new) |
Replaces occurrences of a substring | s.replace("world", "BCA") |
s.split(sep) |
Splits string into a list of words | ["hello", "world"] |
" ".join(list) |
Joins list elements into a single string | " ".join(["Hi", "BCA"]) → "Hi BCA" |
s.find(sub) |
Returns starting index of sub (or -1) |
s.find("world") → 7 |
s.count(sub) |
Counts how many times sub appears |
s.count("l") → 3 |
2. List (list) in Python
A List is an ordered, mutable (changeable) collection of elements enclosed in square brackets [ ]. A single list can hold heterogeneous (different) data types (int, float, str, or even another list).
Key Properties of Lists:
- Ordered: Maintains element order (
0-based indexing). - Mutable: You can add, modify, or remove elements after creation.
- Allows Duplicates: Same value can appear multiple times.
- Heterogeneous: Can store
[101, "Rahul", 85.5, True].
Creating & Modifying a List:
numbers = [10, 20, 30, 40]
# Modifying an element (Mutable)
numbers[1] = 25
print(numbers) # [10, 25, 30, 40]
# Slicing a list
print(numbers[1:3]) # [25, 30]
Important Built-in List Methods:
| Method | What It Does | Example (L = [10, 20, 30]) |
|---|---|---|
L.append(x) |
Adds single element x at the end of the list |
L.append(40) → [10, 20, 30, 40] |
L.insert(i, x) |
Inserts x at specific index i |
L.insert(1, 15) → [10, 15, 20, 30] |
L.extend(seq) |
Adds multiple elements from another sequence | L.extend([50, 60]) |
L.remove(x) |
Removes the first occurrence of value x |
L.remove(20) → [10, 30] |
L.pop(i) |
Removes & returns element at index i (default last) |
L.pop() → returns 30 |
L.sort() |
Sorts the list in ascending order (reverse=True for desc) |
L.sort() |
L.reverse() |
Reverses the elements of the list in-place | L.reverse() |
L.count(x) |
Counts occurrences of x in the list |
L.count(10) → 1 |
List Comprehension (Short-hand List Creation):
A concise way to create a new list from an existing sequence in a single line:
# Create a list of squares of even numbers from 1 to 10
squares = [x**2 for x in range(1, 11) if x % 2 == 0]
print(squares) # [4, 16, 36, 64, 100]
3. Tuple (tuple) in Python
A Tuple is an ordered, immutable (unchangeable) collection of elements enclosed in parentheses ( ).
Key Properties of Tuples:
- Immutable: Once created, elements cannot be added, modified, or deleted.
- Faster & Safer than Lists: Because tuples are read-only, Python allocates fixed memory for them, making them faster than lists and ideal for storing fixed data (like coordinates
(x, y), days of the week, or database records). - Can be used as Dictionary Keys: Unlike lists, tuples are hashable and can be used as keys in a Python dictionary.
Exam Tip — Single Element Tuple: To create a tuple with only one element, you must include a trailing comma:
t = (10,). Without the comma,(10)is treated as a normal integer!
Creating, Packing & Unpacking Tuples:
# Creating a tuple
student = (101, "Ananya", "BCA", 89.5)
# Accessing elements
print(student[1]) # "Ananya"
# student[1] = "Priya" --> ERROR! TypeError: 'tuple' object does not support item assignment
# Tuple Unpacking (assigning tuple elements to individual variables)
roll, name, course, marks = student
print(name, "scored", marks) # Ananya scored 89.5
Built-in Tuple Methods & Functions:
Because tuples cannot be modified, they only have two built-in methods (count() and index()), along with universal functions:
t.count(x)— Returns how many timesxappears in the tuple.t.index(x)— Returns the index of the first occurrence ofx.len(t),max(t),min(t),sum(t),sorted(t)— Universal built-in functions.