Python Forum

Full Version: Basic List Issue
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
So I understand that there are better ways of doing this. I figuered out a couple ways but I am still perplexed as to why this didn't work. I am getting an "IndexError: list index out of range" but I can't figure out why.

Input:
guest_list = ['Guest 1', 'Guest 2', 'Guest 3', 'Guest 4', "Guest 5"]

guest_list_len = (len(guest_list))

x=0

while x <= guest_list_len:
    print (guest_list[x] + ", you are invited to a party!")
    print (str(x), len(guest_list))
    x += 1
Output:
Output:
Traceback (most recent call last): Guest 1, you are invited to a party! 0 5 File "C:/Users/xxxxxxx/PycharmProjects/lists/guest_list.py", line 10, in <module> Guest 2, you are invited to a party! print (guest_list[x] + ", you are invited to a party!") 1 5 IndexError: list index out of range Guest 3, you are invited to a party! 2 5 Guest 4, you are invited to a party! 3 5 Guest 5, you are invited to a party! 4 5 Process finished with exit code 1
As you can see, none of my list indexs are out of range. Thanks for your help!

-Josh

Yay! I figured it out all by myself! The loop should not have been >= because the last element in the list will be numbered one less than the actual count of elements.
The corect loop is while x < guest_list_len:
(May-18-2019, 03:23 PM)rogueakula Wrote: [ -> ]So I understand that there are better ways of doing this.
Yes,for loop with enumerate() would be better,and more Pythonic.
guest_list = ['Guest 1', 'Guest 2', 'Guest 3', 'Guest 4', "Guest 5"]
for index,guest in enumerate(guest_list):
    print (f"{guest}, you are invited to a party!")
    print(index, len(guest_list))
Same output as your code.
More sense to also take people out of list,over it just print len() of gust_list 5 time.
guest_list = ['Guest 1', 'Guest 2', 'Guest 3', 'Guest 4', "Guest 5"]
for people_count,guest in enumerate(guest_list, 1):
    print('-'*15)
    print (f"{guest}, you are invited to a party!")
    print(f"{people_count} guest at party now,{len(guest_list)-people_count} guest now remain in guest_list")
Output:
Guest 1, you are invited to a party! 1 guest at party now,4 guest now remain in guest_list --------------- Guest 2, you are invited to a party! 2 guest at party now,3 guest now remain in guest_list --------------- Guest 3, you are invited to a party! 3 guest at party now,2 guest now remain in guest_list --------------- Guest 4, you are invited to a party! 4 guest at party now,1 guest now remain in guest_list --------------- Guest 5, you are invited to a party! 5 guest at party now,0 guest now remain in guest_list