Python Data Science Jobs & Interviews
20.6K subscribers
191 photos
4 videos
25 files
334 links
Your go-to hub for Python and Data Science—featuring questions, answers, quizzes, and interview tips to sharpen your skills and boost your career in the data-driven world.

Admin: @Hussein_Sheikho
Download Telegram
🐍 Python Tip: Loop with Index using enumerate! 🐍

When you need to iterate through a sequence and also need the index of each item, enumerate() is your best friend! It's more "Pythonic" and cleaner than manually tracking an index.

enumerate() adds a counter to an iterable and returns it as an enumerate object. You can then unpack it directly in your for loop.

my_fruits = ["apple", "banana", "cherry", "date"]

Using enumerate() for a clean loop with index

print("--- Looping with default index ---")
for index, fruit in enumerate(my_fruits):
print(f"Fruit at index {index}: {fruit}")

You can also specify a starting index for the counter

print("\n--- Looping with custom start index (e.g., from 1) ---")
for count, fruit in enumerate(my_fruits, start=1):
print(f"Fruit number {count}: {fruit}")


Output:
--- Looping with default index ---
Fruit at index 0: apple
Fruit at index 1: banana
Fruit at index 2: cherry
Fruit at index 3: date

--- Looping with custom start index (e.g., from 1) ---
Fruit number 1: apple
Fruit number 2: banana
Fruit number 3: cherry
Fruit number 4: date


enumerate() makes your loops more readable and prevents common indexing errors. Give it a try!

#PythonTips #PythonProgramming #LearnPython #Enumerate #CodingHacks

---
By: @DataScienceQ