Strings, lists, tuples, sets and dictionaries — Unit 2 Notes (Python Programming)

BCC302 · Unit 2

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` \to `"AAA"`).
  • Membership: Checking if an item exists using `in` / `not in`.
  • Built-in Functions: `len(seq)` (Length), `max(seq)`, `min(seq)`.

We will explore each data structure in detail.

Next — Strings in Python

1 of 14

Page 2

Wink Notes

B.Tech CSE — 3rd Semester

Python Programming

Unit - 2

2. Strings

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'
```

Next — String Slicing

2 of 14

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"`

Next — String Methods

3 of 14

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.

Next — String Splitting and Joining

4 of 14

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"
```

Next — Lists

5 of 14

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]
```

Next — List Methods: Adding and Removing

6 of 14

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]`.

Next — List Sorting and Comprehensions

7 of 14

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 = [x
2 for x in range(10) if x % 2 == 0]
# Result: [0, 4, 16, 36, 64]
```

Next — Tuples

8 of 14

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.

9.1 Creation

Created using parentheses `()`.

```python
point = (10, 20)
colors = ("red", "green", "blue")
```

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.

Next — Sets

9 of 14

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.

```python
nums = {1, 2, 3, 3, 3, 4}
print(nums) # Output: {1, 2, 3, 4} (Duplicates removed!)
```

  • Unordered: Sets do not record element position. You cannot use indexing (`nums[0]` will crash) or slicing.
  • Unique: Automatically filters out duplicate values.
  • Under the hood, it is implemented as a Hash Table, meaning searching (`3 in nums`) is blindingly fast O(1)O(1), much faster than searching a list O(n)O(n).

Next — Set Mathematical Operations

10 of 14

Page 11

Wink Notes

B.Tech CSE — 3rd Semester

Python Programming

Unit - 2

11. Set Operations

Sets support standard mathematical set theory operations, making them perfect for data filtering.

Let `A = {1, 2, 3}` and `B = {3, 4, 5}`.

  • Union (`|`): All elements from both sets. `A | B` {1,2,3,4,5}\to \{1, 2, 3, 4, 5\}.
  • Intersection (`&`): Elements common to both. `A & B` {3}\to \{3\}.
  • Difference (`-`): Elements in A but not in B. `A - B` {1,2}\to \{1, 2\}.
  • Symmetric Difference (`^`): Elements in either A or B, but NOT both. `A ^ B` {1,2,4,5}\to \{1, 2, 4, 5\}.

11.1 Set Methods

Add an item with `s.add(item)`. Remove an item with `s.remove(item)` (crashes if not found) or `s.discard(item)` (does nothing if not found).

Next — Dictionaries

11 of 14

Page 12

Wink Notes

B.Tech CSE — 3rd Semester

Python Programming

Unit - 2

12. Dictionaries

A Dictionary (`dict`) is an unordered, mutable collection of Key-Value pairs. It is known as a Hash Map or Associative Array in other languages.

12.1 Creation

Created using curly braces `{}` with a colon `:` separating keys and values.

```python
student = {
"name": "Alice",
"age": 20,
"grade": "A"
}
```

12.2 Rules for Keys and Values

  • 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"])`.

Next — Dictionary Methods

12 of 14

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)`

Next — Summary Checklist

13 of 14

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.

14 of 14

Continue in this subject