Monday, August 25, 2025

🐍WORKING WITH ITERABLES IN PYTHON

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() with sort() (reversed returns iterator, does not sort in-place)
  • Forgetting that zip() stops at the shortest iterable
  • Passing non-iterable to any() or all() → TypeError

💡 Try It Yourself

  1. Print the length of a string and a list.
  2. Use sorted() to sort a list of numbers in ascending order.
  3. Loop through a string in reverse using reversed().
  4. Use enumerate() to print indexes and items of a list.
  5. Use zip() to combine two lists of equal length and print pairs.
  6. Check any() and all() for a list of Boolean values.

🖥️ Practice in Browser

No comments:

Post a Comment

🐍What is scikitlearn??