Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Basic List Issue
#1
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:
Reply


Messages In This Thread
Basic List Issue - by rogueakula - May-18-2019, 03:23 PM
RE: Basic List Issue - by snippsat - May-18-2019, 06:01 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  List Comprehension Issue johnywhy 5 606 Jan-14-2024, 07:58 AM
Last Post: Pedroski55
  Python List Issue Aggie64 5 1,706 Jun-30-2022, 09:15 PM
Last Post: Aggie64
  [solved] Basic question on list matchiing paul18fr 7 1,939 May-02-2022, 01:03 PM
Last Post: DeaD_EyE
  List to table issue robdineen 2 1,490 Nov-07-2021, 09:31 PM
Last Post: robdineen
  Calculator code issue using list kirt6405 4 2,322 Jun-11-2021, 10:13 PM
Last Post: topfox
  List index out of range error when attempting to make a basic shift code djwilson0495 4 3,042 Aug-16-2020, 08:56 PM
Last Post: deanhystad
  Issue accessing data from Dictionary/List in the right format LuisSatch 2 2,264 Jul-25-2020, 06:12 AM
Last Post: LuisSatch
  [split] Very basic coding issue aary 4 2,508 Jun-03-2020, 11:59 AM
Last Post: buran
  Very basic coding issue mstichler 3 2,615 Jun-03-2020, 04:35 AM
Last Post: mstichler
  For List Loop Issue Galdain 2 2,096 Dec-31-2019, 04:53 AM
Last Post: Galdain

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020