> ## Documentation Index
> Fetch the complete documentation index at: https://fastapi2day.codewithsiva.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Python Data Structures: Lists, Tuples, Dicts & Sets

> Explore Python's built-in data structures — strings, lists, tuples, sets, dictionaries, and deques — and learn when to use each.

A **data structure** is a way of organising and storing data so it can be accessed, updated, and processed efficiently. Python ships with several powerful built-in data structures — each designed for a different use case. Understanding them deeply will help you write programs that are faster, more readable, and easier to maintain. This page covers all the essential ones: strings, lists, tuples, sets, dictionaries, and deques.

## Overview

| Data Structure | Ordered | Mutable | Duplicates | Example             |
| -------------- | :-----: | :-----: | :--------: | ------------------- |
| `str`          |    ✅    |    ❌    |      ✅     | `"Python"`          |
| `list`         |    ✅    |    ✅    |      ✅     | `[1, 2, 3]`         |
| `tuple`        |    ✅    |    ❌    |      ✅     | `(1, 2, 3)`         |
| `set`          |    ❌    |    ✅    |      ❌     | `{1, 2, 3}`         |
| `dict`         |    ✅    |    ✅    |   Keys: ❌  | `{"name": "Alice"}` |
| `deque`        |    ✅    |    ✅    |      ✅     | `deque([1, 2, 3])`  |

## Strings

A **string (`str`)** is an immutable sequence of Unicode characters used to store text. You can create strings with single quotes, double quotes, or triple quotes for multiline content.

```python theme={null}
name = "Alice"
city = 'Hyderabad'

message = """Welcome
to Python"""
```

### Indexing and Slicing

Access individual characters by position, or extract a substring using `start:stop:step`:

```python theme={null}
text = "Python Programming"

print(text[0])      # P
print(text[-1])     # g
print(text[:6])     # Python
print(text[7:])     # Programming
print(text[::2])    # Pto rgamn
print(text[::-1])   # gnimmargorP nohtyP
```

### String Operators

```python theme={null}
print("Hello " + "Python")    # Hello Python  (concatenation)
print("Hi! " * 3)             # Hi! Hi! Hi!   (repetition)
print("Py" in "Python")       # True
print("Java" not in "Python") # True
```

### Common String Methods

```python theme={null}
text = " hello python "

print(text.upper())                    # ' HELLO PYTHON '
print(text.strip())                    # 'hello python'
print(text.replace("python", "world")) # ' hello world '
print(text.find("python"))             # 7
print(text.count("o"))                 # 2
```

### Splitting and Joining

```python theme={null}
text = "Python,Java,C++"

languages = text.split(",")
print(languages)                    # ['Python', 'Java', 'C++']
print("-".join(languages))          # Python-Java-C++
```

### f-Strings

Use f-strings for readable string interpolation:

```python theme={null}
name = "Alice"
age = 20
print(f"{name} is {age} years old.")  # Alice is 20 years old.
```

<Note>
  Strings are **immutable** — you cannot change a character in place. To "modify" a string, create a new one: `text = "J" + text[1:]`.
</Note>

## Lists

A **list** is an ordered, mutable collection that can hold elements of different data types. It is the most versatile and commonly used data structure in Python.

```python theme={null}
fruits = ["Apple", "Banana", "Orange"]
mixed  = [1, "Python", 3.14, True]
empty  = []
```

### Accessing Elements

Lists support indexing and slicing just like strings:

```python theme={null}
fruits = ["Apple", "Banana", "Orange", "Mango"]

print(fruits[0])     # Apple
print(fruits[-1])    # Mango
print(fruits[:2])    # ['Apple', 'Banana']
print(fruits[::-1])  # ['Mango', 'Orange', 'Banana', 'Apple']
```

### Common List Methods

```python theme={null}
numbers = [10, 20, 30]

numbers.append(40)          # [10, 20, 30, 40]
numbers.insert(1, 15)       # [10, 15, 20, 30, 40]
numbers.extend([50, 60])    # [10, 15, 20, 30, 40, 50, 60]

numbers.remove(20)          # removes first occurrence of 20
numbers.pop()               # removes and returns the last element

numbers.sort()
numbers.reverse()

print(numbers)
```

### List Comprehension

Comprehensions provide a concise, Pythonic way to build lists:

```python theme={null}
squares = [x * x for x in range(1, 6)]
print(squares)  # [1, 4, 9, 16, 25]

evens = [x for x in range(10) if x % 2 == 0]
print(evens)    # [0, 2, 4, 6, 8]
```

## Tuples

A **tuple** is an ordered, **immutable** collection. Once created, it cannot be changed, making it ideal for data that should remain constant.

```python theme={null}
colors = ("Red", "Green", "Blue")
single = (10,)   # Note the trailing comma for single-element tuples
empty  = ()
```

<Warning>
  A single-element tuple **must** include a trailing comma: `(10,)`. Without it, `(10)` is just an integer in parentheses.
</Warning>

### Accessing Elements

Tuples support the same indexing and slicing as lists:

```python theme={null}
colors = ("Red", "Green", "Blue", "Yellow")

print(colors[0])    # Red
print(colors[-1])   # Yellow
print(colors[:2])   # ('Red', 'Green')
```

### Tuple Packing and Unpacking

```python theme={null}
student = ("Alice", 20, "Python")
name, age, course = student

print(name)    # Alice
print(age)     # 20
print(course)  # Python
```

## Sets

A **set** is an unordered, mutable collection of **unique** elements. Duplicates are removed automatically, making sets perfect for membership testing and eliminating redundancy.

```python theme={null}
numbers = {10, 20, 30, 20}
print(numbers)  # {10, 20, 30}
```

<Note>
  Use `set()` to create an empty set. Using `{}` creates an empty **dictionary**, not a set.
</Note>

### Common Set Methods

```python theme={null}
numbers = {10, 20, 30}

numbers.add(40)
numbers.remove(20)        # raises KeyError if not found
numbers.discard(50)       # no error if element doesn't exist

print(numbers)  # {10, 30, 40}
```

### Set Operations

```python theme={null}
a = {1, 2, 3}
b = {3, 4, 5}

print(a | b)    # Union:               {1, 2, 3, 4, 5}
print(a & b)    # Intersection:        {3}
print(a - b)    # Difference:          {1, 2}
print(a ^ b)    # Symmetric Difference:{1, 2, 4, 5}
```

## Dictionaries

A **dictionary (`dict`)** stores data as **key-value pairs**. Keys must be unique and immutable; values can be any type. Dictionaries preserve insertion order in Python 3.7+.

```python theme={null}
student = {
    "name": "Alice",
    "age": 20,
    "course": "Python"
}
```

### Accessing Values

```python theme={null}
print(student["name"])          # Alice — raises KeyError if missing
print(student.get("age"))       # 20
print(student.get("grade", "N/A"))  # N/A (safe default)
```

### Adding, Updating, and Removing

```python theme={null}
student["city"] = "Hyderabad"   # add new key
student["age"] = 21              # update existing key

student.pop("city")              # remove key
del student["course"]
```

### Iterating a Dictionary

```python theme={null}
for key, value in student.items():
    print(key, "->", value)
```

### Dictionary Comprehension

```python theme={null}
squares = {x: x * x for x in range(1, 6)}
print(squares)  # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
```

## deque

A **`deque`** (double-ended queue) from Python's `collections` module supports fast `O(1)` insertion and deletion from **both ends** — far more efficient than a list for queue-like operations.

```python theme={null}
from collections import deque

dq = deque([10, 20, 30])

dq.append(40)       # add to right:  [10, 20, 30, 40]
dq.appendleft(5)    # add to left:   [5, 10, 20, 30, 40]

dq.pop()            # remove from right: [5, 10, 20, 30]
dq.popleft()        # remove from left:  [10, 20, 30]

print(dq)           # deque([10, 20, 30])
```

### Rotating a deque

```python theme={null}
dq = deque([1, 2, 3, 4])

dq.rotate(1)     # deque([4, 1, 2, 3])
print(dq)

dq.rotate(-2)    # deque([2, 3, 4, 1])
print(dq)
```

<Tip>
  Prefer `deque` over `list` when you frequently add or remove elements from the **beginning** of a collection. A `list.insert(0, x)` is `O(n)`; `deque.appendleft(x)` is `O(1)`.
</Tip>
