Click here to Skip to main content
15,867,568 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
menu = [
["bacon", "eggs"]"
    ["bacon", "spam", "eggs ", "cheese"],
    ["sausages", "cheese", "spam", "coco cola"],
    ["spam", "spam", "spam"],
    ["eggs", "cheese", "tea", ]
]

for meal in menu:
    for x in range(len(meal) - 1, -1, -1):
        if meal[x] == "spam":
            del meal[x]
    print(meal[len(meal)-1], meal[len(meal)-2], sep="and")


What I have tried:

i didn't try anything because
meal[len(meal)-1]
and
meal[len(meal)-2] 
do not seem out of the meal range
Posted
Updated 15-Sep-21 1:20am

Quote
Python
for x in range(len(meal) - 1, -1, -1):
The second parameter to the range function is the end value for the sequence. You are looping from the last item in the list to -1.

meal[-1] will be out of range.


Edit:
The problem is with the ["spam", "spam", "spam"] entry. You have removed all items from the array, so len(meal) will be 0, and both meal[0 - 1] and meal[0 - 2] will be out of range.

You need to test that there are at least two elements in the array before trying to print it.
Python
if len(meal) > 1:
    print(meal[len(meal)-1], meal[len(meal)-2], sep="and")
 
Share this answer
 
v2
Comments
Member 15331575 15-Sep-21 7:10am    
thank you, but the error is line 13, in <module>
print(meal[len(meal)-1], meal[len(meal)-2], sep="and")IndexError: list index out of range
so the error is in print(meal[len(meal)-1], meal[len(meal)-2], sep="and")
Richard Deeming 15-Sep-21 7:13am    
OK, so the error relates to the ["spam", "spam", "spam"] array. You have removed all items from the array, so len(meal) is 0. Both meal[0 - 1] and meal[0 - 2] will be out of range.
Member 15331575 15-Sep-21 7:19am    
thank you so much
Python
menu = [
["bacon", "eggs"]"
#                ^ may be the quote here do not help
    ["bacon", "spam", "eggs ", "cheese"],
    ["sausages", "cheese", "spam", "coco cola"],
    ["spam", "spam", "spam"],
    ["eggs", "cheese", "tea", ]
#                           ^ may be the comma here do not help
]
 
Share this answer
 
v2
Comments
Richard MacCutchan 15-Sep-21 7:46am    
No, the comma is fine. See Solution 1.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900