Iterable Basics
What are Iterables?
In Python, an iterable is an object that can be looped over or iterated. It's a fundamental concept that allows you to process collections of data efficiently. Common examples of iterables include:
- Lists
- Tuples
- Dictionaries
- Sets
- Strings
- Generators
graph LR
A[Iterable] --> B[List]
A --> C[Tuple]
A --> D[Dictionary]
A --> E[Set]
A --> F[String]
A --> G[Generator]
Basic Iteration Techniques
Using for Loops
The most common way to iterate through an iterable is using a for
loop:
## Iterating through a list
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
## Iterating through a dictionary
student_scores = {'Alice': 85, 'Bob': 92, 'Charlie': 78}
for name, score in student_scores.items():
print(f"{name}: {score}")
Iteration Methods
Method |
Description |
Example |
iter() |
Creates an iterator object |
iterator = iter([1, 2, 3]) |
next() |
Retrieves next item from iterator |
first_item = next(iterator) |
Advanced Iteration Concepts
List Comprehensions
List comprehensions provide a concise way to create lists based on existing iterables:
## Square numbers from 0 to 9
squares = [x**2 for x in range(10)]
print(squares) ## [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
## Filter even numbers
even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers) ## [0, 2, 4, 6, 8]
Generator Expressions
Similar to list comprehensions, but more memory-efficient:
## Generator expression
square_generator = (x**2 for x in range(10))
for square in square_generator:
print(square)
Key Takeaways
- Iterables are fundamental to Python's data processing
- Multiple ways exist to iterate through collections
- List comprehensions and generators offer powerful transformation techniques
By understanding these basics, you'll be well-prepared to handle iterable transformations in your Python projects, whether you're working on data analysis, web development, or scientific computing with LabEx tools.