Python enumerate() function: index and value pairs

😊❤️ Todays topic: Topic: enumerate() function in Python ============== The enumerate() function is used to get both the index and the value while looping. Without enumerate(): names = ["A", "B", "C"] index = 0 for name in names: print(index, name) index += 1 Using enumerate(): names = ["A", "B", "C"] for index, name in enumerate(names): print(index, name) Output: 0 A 1 B 2 C Explanation: enumerate() automatically gives both index and value. Starting index from custom value: names = ["A", "B", "C"] for index, name in enumerate(names, start=1): print(index, name) Output: 1 A 2 B 3 C Convert to list: names = ["A", "B"] print(list(enumerate(names))) Output: [(0, 'A'), (1, 'B')] Key Points: Returns (index, value) pairs Default index starts from 0 Can customize starting index Interview Insight: enumerate() improves readability and avoids manual index handling, which reduces errors in loops. Quick Question: What will be the output? items = ["x", "y"] print(list(enumerate(items, start=2))) #Python #Programming #Coding #InterviewPreparation #Developers

To view or add a comment, sign in

Explore content categories