How to use other way of iterating items


#1

since there’s two ways of iterating items in a list :

iterating%20over%20a%20list%20in%20a%20function|405x436

then how do i use the other way in this code?

n = [“Michael”, “Lieberman”]

Add your function here

def join_strings(words):
result = “”
for word in words:
result += word
return result

print join_strings(n)


https://www.codecademy.com/courses/learn-python/lessons/lists-and-functions/exercises/using-strings-in-lists-in-functions?action=resume_content_item

thank u for the help! also please explain the

for i in range(len(list)):

i don’t get it that much. thank you!!


#2

One way to iterate over a list is by index.

for i in range(len(my_list):
    print (my_list[i])

The other way is to iterate over the values…

for value in my_list:
    print (value)

We may combine both forms in a single loop using the enumerate built-in. This will iterate over both index and value…

for i, x in enumerate(my_list):    # i is the index, x is the value
    print ("[{}] => {}".format(i, x))

To review,

range(start, end, stride)

Eg.

my_list = [1,1,2,3,5,8,13,21,34,55]

Excluding zero as the first term, the above is the first ten terms of a Fibonacci sequence. We know it is ten terms because,

len(my_list)   =>  10

To iterate over this list by index, we would write,

for i in range(len(my_list)):

A range covers an interval from start to end, but not including the very last value. The default difference between terms (stride) is 1 and the default starting value is 0. This works great with lists since they are zero-indexed.

range(len(my_list))    =>  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Notice there are still ten elements in the list of integers? (range() can only work with integers.)