Iterables are objects that can be looped over, such as lists, tuples, sets, dictionaries, and strings. Python provides many built-in functions to work with them efficiently.
What is an Iterable?
An iterable is any Python object capable of returning its elements one at a time, allowing it to be looped over in a for loop.
Examples of iterables:
list: [1, 2, 3]tuple: (1, 2, 3)set: {1, 2, 3}dict: {"a":1, "b":2}string: "Python"
Common Built-in Functions for Iterables
# Length of an iterable
fruits = ["apple", "banana", "cherry"]
print(len(fruits)) # 3
# Sorting
nums = [5, 2, 8, 1]
print(sorted(nums)) # [1, 2, 5, 8]
# Reverse iteration
for char in reversed("Python"):
print(char, end=" ") # n o h t y P
# Enumerate: get index and value
for i, fruit in enumerate(fruits):
print(i, fruit)
# Zip: combine multiple iterables
names = ["Alice", "Bob"]
ages = [25, 30]
for name, age in zip(names, ages):
print(name, age)
# any() and all()
bool_list = [True, False, True]
print(any(bool_list)) # True
print(all(bool_list)) # False
Common Mistakes
- Calling
len()on non-iterable (e.g.,len(5)→ TypeError) - Using
sorted()on non-iterable → TypeError - Confusing
reversed()withsort()(reversed returns iterator, does not sort in-place) - Forgetting that
zip()stops at the shortest iterable - Passing non-iterable to
any()orall()→ TypeError
💡 Try It Yourself
- Print the length of a string and a list.
- Use
sorted()to sort a list of numbers in ascending order. - Loop through a string in reverse using
reversed(). - Use
enumerate()to print indexes and items of a list. - Use
zip()to combine two lists of equal length and print pairs. - Check
any()andall()for a list of Boolean values.
No comments:
Post a Comment