Strings, lists, tuples, sets and dictionaries notes — Unit 2
Free unit-wise study notes on strings, lists, tuples, sets and dictionaries for Python Programming, Semester 3 of B.Tech — Computer Science & Engineering — key concepts, examples, important questions and a revision checklist for semester exams.
Mastering Python's built-in data structures. Covers Strings and slicing, mutable Lists, immutable Tuples, unique Sets, and Key-Value Dictionaries, along with their respective built-in methods.
Notebook — 14 pages
Page 1
Wink Notes
B.Tech CSE — 3rd Semester
Python Programming
— Unit - 2 —
1. Introduction to Sequences
In Python, a sequence is an ordered collection of items. The fundamental sequences are Strings, Lists, and Tuples. Because they are ordered, they share several common operations.
⇒1.1 Common Sequence Operations
Indexing: Accessing a single item using `seq[i]`.
Slicing: Extracting a subset using `seq[start:stop:step]`.
Concatenation: Joining two sequences using `+`.
Repetition: Repeating a sequence using `` (e.g., `"A" 3` → `"AAA"`).
Membership: Checking if an item exists using `in` / `not in`.
A string (`str`) is an ordered sequence of characters. Strings in Python are immutable (they cannot be changed in place after creation).
⇒2.1 Creation
Can be created using single, double, or triple quotes (for multi-line strings).
```python s1 = 'Hello' s2 = "World" s3 = '''This is a multi-line string''' ```
⇒2.2 Indexing
Python supports both positive indexing (starting from `0` at the left) and negative indexing (starting from `-1` at the right).
```python text = "PYTHON" # text[0] is 'P', text[1] is 'Y' # text[-1] is 'N', text[-2] is 'O' ```
Page 3
Wink Notes
B.Tech CSE — 3rd Semester
Python Programming
— Unit - 2 —
3. String Slicing
Slicing allows you to extract a substring. Syntax: `string[start : stop : step]`
`start`: The starting index (inclusive). Defaults to 0.
`stop`: The ending index (exclusive). Defaults to length of string.
`step`: The jump size. Defaults to 1.
⇒3.1 Slicing Examples
```python text = "UNIVERSITY" print(text[0:4]) # "UNIV" (indices 0, 1, 2, 3) print(text[4:]) # "ERSITY" (index 4 to end) print(text[:3]) # "UNI" (start to index 2) print(text[0:6:2]) # "UIE" (jumps by 2) ```
⇒3.2 The Reversal Trick
A very common interview trick to reverse a string in one line is to use a step of `-1`.
`print(text[::-1]) # Output: "YTISREVINU"`
Page 4
Wink Notes
B.Tech CSE — 3rd Semester
Python Programming
— Unit - 2 —
4. String Methods
Because strings are objects, they have built-in methods. Note: Since strings are immutable, these methods do not change the original string; they return a new modified string.
⇒4.1 Common Formatting Methods
`s.upper()` / `s.lower()`: Converts to all uppercase/lowercase.
`s.title()`: Capitalizes the first letter of every word.
`s.strip()`: Removes leading and trailing whitespace (or specific characters).
`s.replace(old, new)`: Replaces occurrences of a substring.
⇒4.2 Inspection Methods
`s.find(sub)`: Returns the lowest index where substring is found. Returns `-1` if not found.
`s.count(sub)`: Returns the number of non-overlapping occurrences of a substring.
`s.isdigit()`: Returns True if all characters are numbers (0-9).
`s.isalpha()`: Returns True if all characters are alphabetic.
Page 5
Wink Notes
B.Tech CSE — 3rd Semester
Python Programming
— Unit - 2 —
5. String Splitting and Joining
Two of the most frequently used methods for text processing and data cleaning.
⇒5.1 `split()`
Breaks a string into a List of substrings based on a delimiter. If no delimiter is provided, it splits by any whitespace.
```python data = "apple,banana,cherry" fruits = data.split(",") # fruits is now ['apple', 'banana', 'cherry'] ```
⇒5.2 `join()`
The exact opposite of split. It takes an iterable (like a List) of strings and concatenates them together, using a specific string as a separator.
```python words = ["Python", "is", "fun"] sentence = " ".join(words) # sentence is now "Python is fun" ```
Page 6
Wink Notes
B.Tech CSE — 3rd Semester
Python Programming
— Unit - 2 —
6. Lists
A List (`list`) is an ordered, mutable collection of items. It is equivalent to a dynamic array in C/Java (like `ArrayList`), but far more flexible.
⇒6.1 Creation and Properties
Created using square brackets `[]`.
Mutable: You can change, add, or remove items after creation.
Heterogeneous: A single list can hold different data types. `my_list = [10, "Hello", 3.14, True]`
Dynamic: Grows and shrinks in memory automatically.
Because lists are sequences, indexing (`my_list[0]`) and slicing (`my_list[1:3]`) work exactly the same as they do for strings.
```python nums = [10, 20, 30] nums[1] = 99 # Allowed because Lists are mutable # nums is now [10, 99, 30] ```
Page 7
Wink Notes
B.Tech CSE — 3rd Semester
Python Programming
— Unit - 2 —
7. List Methods: Adding and Removing
⇒7.1 Adding Items
`lst.append(item)`: Adds an item to the extreme end of the list.
`lst.insert(index, item)`: Inserts an item at a specific index, shifting subsequent items to the right.
`lst.extend(iterable)`: Appends all items from another list (or iterable) to the end of the current list.
⇒7.2 Removing Items
`lst.remove(item)`: Removes the first occurrence of the specified value. Raises ValueError if not found.
`lst.pop(index)`: Removes and returns the item at the specified index. If no index is given, it pops the last item.
`lst.clear()`: Empties the entire list.
`del lst[index]` (Keyword, not a method): Deletes an item by index, or can delete an entire slice `del lst[1:3]`.
Page 8
Wink Notes
B.Tech CSE — 3rd Semester
Python Programming
— Unit - 2 —
8. List Operations
⇒8.1 Sorting and Reversing
`lst.sort()`: Sorts the list in-place (modifies the original list). Ascending by default. Use `lst.sort(reverse=True)` for descending.
`sorted(lst)`: A built-in function that returns a new sorted list, leaving the original unchanged.
`lst.reverse()`: Reverses the order of the list in-place.
⇒8.2 List Comprehensions
A highly "Pythonic", concise way to create lists based on existing iterables.
Syntax: `[expression for item in iterable if condition]`
Example: Create a list of the squares of even numbers from 0 to 9.
```python squares = [x2 for x in range(10) if x % 2 == 0] # Result: [0, 4, 16, 36, 64] ```
Page 9
Wink Notes
B.Tech CSE — 3rd Semester
Python Programming
— Unit - 2 —
9. Tuples
A Tuple (`tuple`) is an ordered, immutable collection of items.
Note: To create a tuple with a single item, you MUST include a trailing comma, otherwise Python treats it as a mathematical parenthesis: `single = (5,)`.
⇒9.2 Why use Tuples?
Since lists do everything tuples do and more (they are mutable), why do tuples exist?
Safety: Write-protects data that should not be changed (e.g., coordinates, RGB values).
Speed: Iterating through a tuple is slightly faster than a list because of memory optimization.
Dictionary Keys: Only immutable objects can be used as keys in a dictionary. Tuples can be keys; lists cannot.
Page 10
Wink Notes
B.Tech CSE — 3rd Semester
Python Programming
— Unit - 2 —
10. Sets
A Set (`set`) is an unordered, mutable collection of unique items.
⇒10.1 Creation and Properties
Created using curly braces `{}` or the `set()` function.
Keys: Must be Unique and Immutable (Strings, Numbers, Tuples). You cannot use a List as a key.
Values: Can be anything. Mutable, immutable, duplicates allowed, even other dictionaries (nested dicts).
Instead of indexing by a number (like lists), you index by the Key: `print(student["name"])`.
Page 13
Wink Notes
B.Tech CSE — 3rd Semester
Python Programming
— Unit - 2 —
13. Dictionary Methods
⇒13.1 Accessing and Modifying
`d.get(key, default)`: Safely retrieves a value. If the key doesn't exist, it returns `None` (or the default) instead of crashing the program with a KeyError.
Adding/Updating: `d["new_key"] = value`. If key exists, it updates. If not, it creates a new pair.
`d.pop(key)`: Removes the key-value pair and returns the value.
⇒13.2 Iterating through a Dictionary
When you use a standard `for` loop on a dictionary (`for x in d:`), it iterates over the Keys by default.
To access everything, use the view methods:
`d.keys()`: Returns a view of all keys.
`d.values()`: Returns a view of all values.
`d.items()`: Returns a view of tuples `(key, value)`. Best for looping: `for key, val in student.items(): print(key, val)`
Page 14
Wink Notes
B.Tech CSE — 3rd Semester
Python Programming
— Unit - 2 —
14. Summary Checklist
Mastering these four data structures is essential for technical interviews.
⇒14.1 The Big Picture
List `[]`: Ordered, Mutable. Use when you have a sequence of items that might change.
Tuple `()`: Ordered, Immutable. Use for fixed data records.
Set `{}`: Unordered, Mutable, Unique. Use to remove duplicates or perform fast membership testing.
Dict `{k:v}`: Unordered, Mutable, Key-Value. Use when establishing a relationship/mapping between two pieces of data.
⇒14.2 Interview / Exam Prep
Write a Python script to reverse a string without using the `[::-1]` slice.
Write a list comprehension to flatten a 2D list.
Given a string of text, use a Dictionary to count the frequency of each word.
Explain why a List cannot be used as a Dictionary key.