Trouble understanding for loops and the range(len()) function combination

Hey all. I have a general question regarding for loops and their combination with the range(len()) function as in my example below.

for items in range(len(names))

I do not understand conceptually what happens here and any insight would be appreciated.

We can use print statements to demonstrate what is happening here. You have two functions being used range() and len(). range() provides us with a list of sequential numbers up to but not including the final number that can be iterated through, for example range(3) gives us the list [0, 1, 2]. len() gives us the length of a list, so len([0, 1, 2]) would give us the integer ‘3’ as there are three elements.

So lets put this together in an example using the syntax from your question:

names = ['Steve', 'Jodie', 'Muhammad', 'Alex', 'Enorah']

print('length of names is ' + str(len(names)))
# this prints 'length of names is 5'
# this means that there are 5 elements in names

for item in range(len(names)):
# as we know the length of names is 5, range(len(names)) is the same as range(5), which gives 
# us the list [0,1,2,3,4]. This list is then iterated through by the for loop, so the first
# item is 0, then 1 etc.
  print(item)
# This then prints the value of item for each iteration, thus it prints 0, 1, 2, 3, 4 to the console.

I hope this helped to explain it a bit better, let me know if you have any other questions!

3 Likes

Thanks Adam! That is very helpful and I do appreciate you taking the time. One other question, could I use that same process to print the names within the list as well?

You could indeed! if done this way, then you would use item as the index, and do

for item in range(len(names)):
  print(names[item])

or, to make it much easier, just loop through the names themselves

for name in names:
  print(name)

Thank you so much Adam! I played around with what you’ve shown me. and have a much better understanding now.