# Iterables

### What is an Iterable?

When a programming language goes through a collection of elements (say, a list) in any fashion, it is said to be "iterating over" that collection. Collections of elements that can be iterated over by Python are known as iterables.

We'll be discussing three iterables in this section: lists, tuples, and ranges.&#x20;

### Lists

This is the most common form of iterable, and one you've almost certainly already used. It looks something like this:

```python
>>> lst = [1, 2, 3, 4]
```

You can index into it to retrieve an element, starting at zero.

```python
>>> lst[0]
1
>>> lst[1]
2
```

You can also edit this list in a similar fashion.

```python
>>> lst[0] = 5
>>> lst
[5, 2, 3, 4]
```

### Tuples

Tuples are extremely similar to lists, with one key difference — while lists can be edited (are mutable), tuples are immutable. You cannot change them once you've created them.&#x20;

```python
>>> t = (1, 2, 3, 4)
>>> t[0]
1
>>> t[0] = 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
```

Note the error: It essentially states that tuples cannot be assigned elements once they are created.

### Range

You might have used the `range(start, stop, step)` function before in for loops, something like the following:

```python
for i in range(1, 10, 2):
    print(i)
# prints 1 3 5 7 9
```

We have not, however, stopped to consider what the call to the range function returns. Let's instead investigate this:

```python
>>> r = range(10)
>>> r
range(0, 10)
>>> type(r)
class 'range'
```

Note how the `range` function doesn't return a list or a tuple but something else unique. This something else unique is an **immutable sequence**. The following example gives us insight on the immutability of range:

```python
>>> r[3] = 4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'range' object does not support item assignment
```

Notice how the error is the same as the one for tuples! We can also perform the same operations as that of lists on ranges — indexing, slicing and so on.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://calnotes.gitbook.io/cs61a-guidebook/structures-of-data/iterables.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
