Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleaner Way to Take Items from One List to Another

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!

like image 765
user2717129 Avatar asked Aug 26 '13 08:08

user2717129


People also ask

How do you transfer elements from one list to another?

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 you exclude items from a list in Python?

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.

How do I remove a list from a nested list in Python?

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.


2 Answers

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)
like image 170
Hyperboreus Avatar answered Oct 14 '22 14:10

Hyperboreus


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 ) )
like image 42
Alex Avatar answered Oct 14 '22 16:10

Alex