How can I get the index of each element in a sequence while iterating with a for loop?

How can I access the index of each element while iterating over a sequence using a for loop?

xs = [8, 23, 45] for index, x in enumerate(xs, 1): print(“item #{} = {}”.format(index, x)) Desired output: item #1 = 8 item #2 = 23 item #3 = 45

Hello AnjyYadav,

To access the index while iterating over a sequence in Python, you can use the built-in enumerate() function. This is considered more Pythonic than manually indexing using for i in range(len(xs)) or managing an additional state variable.

Here’s how you can use enumerate(): xs = [8, 23, 45]

for idx, x in enumerate(xs): print(idx, x)

This will output: 0 8 1 23 2 45

For more information, you can refer to PEP 279.

Hey Anjuyadav,

Python 2.x

for index, item in enumerate(iterable, start=1): print index, item

Python 3.x and later

for index, item in enumerate(iterable, start=1): print(index, item)

This code snippet demonstrates how to use the enumerate() function with the start parameter to begin indexing from 1 instead of the default 0.

Hello AnjuYadav,

Here are twelve examples of how to access indices and their corresponding array elements using various methods in Python:

  1. Looping elements with a counter and += operator:

items = [8, 23, 45, 12, 78] counter = 0

for value in items: print(counter, value) counter += 1

  1. Iterating elements using enumerate():

items = [8, 23, 45, 12, 78]

for i in enumerate(items): print(“index/value”, i)

  1. Getting list elements and their indices separately:

items = [8, 23, 45, 12, 78]

for index, value in enumerate(items): print(“index”, index, “for value”, value)

  1. Changing the index value increment:

items = [8, 23, 45, 12, 78]

for i, item in enumerate(items, start=100): print(i, item)

  1. Automatic counter incrementation with range(len(...)):

items = [8, 23, 45, 12, 78]

for i in range(len(items)): print(“Index:”, i, “Value:”, items[i])

  1. Using a for loop inside a function:

items = [8, 23, 45, 12, 78]

def enum(items, start=0): counter = start

for value in items:
    print(counter, value)
    counter += 1

enum(items)

  1. Using a while loop:

items = [8, 23, 45, 12, 78] counter = 0

while counter < len(items): print(counter, items[counter]) counter += 1

  1. Using a yield statement to return a generator object: def createGenerator():
    items = [8, 23, 45, 12, 78]

    for (j, k) in enumerate(items): yield (j, k)

generator = createGenerator()

for i in generator: print(i)

  1. Using an inline expression with a lambda and for loop: items = [8, 23, 45, 12, 78]

xerox = lambda upperBound: [(i, items[i]) for i in range(0, upperBound)] print(xerox(5))

  1. Iterating over two lists simultaneously using zip(): items = [8, 23, 45, 12, 78] indices = []

for index in range(len(items)): indices.append(index)

for item, index in zip(items, indices): print(“{}: {}”.format(index, item))

  1. Looping over two lists with a while loop and iter() & next():

items = [8, 23, 45, 12, 78] indices = range(len(items))

iterator1 = iter(indices) iterator2 = iter(items)

try: while True: i = next(iterator1) element = next(iterator2) print(i, element) except StopIteration: pass

  1. Iterating list elements inside a class’s static method: items = [8, 23, 45, 12, 78]

class ElementPlus: @staticmethod def indexForEachOfMy(iterable): for pair in enumerate(iterable): print(pair)

ElementPlus.indexForEachOfMy(items)

These examples demonstrate different approaches to iterate over list elements and their indices in Python.