Reputation: 75
I am trying to solve the following problem in Python 3.
Loop through each element in word_list, printing the current element and the next element, separated by a space, in each loop
The problem is that I exceed the range when I get to the last index, but am not sure how to modify the range object to fix this problem. Any ideas on how to modify this?
Code:
word_list=["Willie", "likes", "sleeping", "and", "eating"]
phrase_str=""
for i in range(len(word_list)):
phrase_str= word_list[i] + " " + word_list[i+1]
print(phrase_str)
Output
Willie likes
likes sleeping
sleeping and
and eating
Error
IndexError Traceback (most recent call last)
<ipython-input-28-aba2a7894c1a> in <module>
2 phrase_str=""
3 for i in range(len(word_list)):
----> 4 phrase_str= word_list[i] + " " + word_list[i+1]
5 print(phrase_str)
6
IndexError: list index out of range
Upvotes: 0
Views: 840
Reputation: 1907
If you are coding in python always use "Pythonic" approach:
word_list=["Willie", "likes", "sleeping", "and", "eating"]
for w1, w2 in zip(word_list, word_list[1:]):
print(w1, w2)
Output:
Willie likes
likes sleeping
sleeping and
and eating
Upvotes: 3
Reputation: 173
Hi this is an arbitary error!
The length of the list is 5, however indexing starts at 0, so the first element corresponds with index 0. hence the list range is out of bounds, juat use [len(word_list) - 1] and lop through! Hope this helps!
Upvotes: 1
Reputation: 145
if you make len(word_list) - 1
it won't come to the end of list
word_list=["Willie", "likes", "sleeping", "and", "eating"]
phrase_str=""
for i in range(len(word_list) - 1):
phrase_str= word_list[i] + " " + word_list[i+1]
print(phrase_str)
Upvotes: 1