I've been writing a text adventure game, and at one point I need to take an item, which is given by user input, from one list and move it to another list. Specifically, is there any way to get the index of an item when you know the item name besides something like:
list_one = ["item one", "item two"]
index_one = list_one.index("item one")
The code I'm using in my script is:
player.items.append(start_room.items.pop(start_room.items.index(next)))
Where next is the input, and this seems very messy. If there's an easier way to go about this, let me know. Thanks!
Method : Using pop() + insert() + index() This particular task can be performed using combination of above functions. In this we just use the property of pop function to return and remove element and insert it to the specific position of other list using index function.
How do I remove a specific element from a list in Python? The remove() method removes the first matching element (which is passed as an argument) from the list. The pop() method removes an element at a given index, and will also return the removed item.
Remove items from a Nested List. If you know the index of the item you want, you can use pop() method. It modifies the list and returns the removed item. If you don't need the removed value, use the del statement.
If you already know the item, there is no need to call index
or pop
or whatever:
list_one.remove (item)
list_two.append (item)
I prefer to use return of pop()
method :
list_two.append( list_one.pop( list_one.index( item ) ) )
And if suddenly you decide to need index, you don't need to change much :
i = list_one.index( item )
list_two.append( list_one.pop( i ) )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With