Ruth goes shopping today, so she is busy making a shopping list. She wrote down things…
- User
Ruth goes shopping today, so she is busy making a shopping list.
She wrote down things that she would like to buy at the grocery store. All of these things are in the given shopping_list variable, it has already been created.
When sneaking a look at the fridge, she noticed that there was some milk left and changed her mind about buying a new one. It got crossed out of the list. And, finally, she added a "brownie", and it became the last item Ruth had put on the list.
Now you try to remove "milk" from the given variable shopping_list, and add "brownie" to it.
DON'T print the results.
You can add an item with list.append() and delete it with list.remove(). Hint by avatar Stefan Grafik Consider creating a 'def replace()' function yourself. Then return the new list (don't print). Was this hint helpful? Write a program in Python 3 Report a typo AI Code Editor IDE100 1
remove a product and add another one; do not create a variable, it has already been created
Com
- Assistant
Sure, let's write a Python function called
update_shopping_listthat will modify theshopping_listby removing "milk" and adding "brownie". Here is the code for the function:pythondef update_shopping_list(shopping_list): shopping_list.remove("milk") shopping_list.append("brownie") return shopping_listThis function assumes that "milk" is indeed present in the
shopping_listand uses theremove()method to delete it. Then it adds "brownie" using theappend()method and returns the updated list. - User
Let's say there's a list values = ['delete me', 'do not', 'delete me'].
What are the correct ways to delete the first element?
Hint by avatar Nick C pop() takes the last element Was this hint helpful? Select one or more options from the list Report a typo
values.remove('delete me')
values.pop()
values.del(0)
values.remove(0)
del values[0]
values.pop('delete me')
- Assistant
To delete the first element
'delete me'from the listvalues = ['delete me', 'do not', 'delete me'], you have a few correct options:-
Using the
remove()method: This removes the first occurrence of a specified value.pythonvalues.remove('delete me') -
Using the
delstatement: This removes an element at a specified index.pythondel values[0]
The following options are incorrect:
values.pop()would remove the last element, not the first.values.pop('delete me')is invalid becausepop()takes an index, not a value.values.del(0)is not a valid syntax in Python.values.remove(0)is incorrect because it attempts to remove the element0, which doesn't exist in the list.
-