Home > Software engineering >  What is the pros and cons of different ways of accessing list elements?
What is the pros and cons of different ways of accessing list elements?

Time:09-01

I have question based on looping through iterable objects with a counter.

What is the benefit / advantage of either method below as they do the same thing:

list = ["a", "b", "c", "d"]

 #Method 1

for index in range(len(list)):
    value = list[index]
    print(index, value)



#Method 2 

for index, values in enumerate(list):
    print(index, values)

CodePudding user response:

My way of using for loops is:

If you just need the values of a list, just get the values:

l = ["a", "b", "c", "d"]

for value in l:
   print(l)

If you need the index and the value, use enumerate:

for index, value in enumerate(l):
   print(index, value)

If you need to loop over two lists at the same time, you could use range to get the indexes:

l2 = l = ["e", "f", "g", "h"]
for index in range(len(list)):
    print(index, l[index], l2[index])

however its more pythonic to use a zip:

for val1, val2 in zip(l, l2):
    print(val1, val2)

If you want to do something a number of times, rather than looping over an object, use range:

n = 10

for i in range(n):
    print(i)

However as always, just use whatever is best for your use case and is the most readable.

  • Related