Mathime
Mathime

Reputation: 1490

How to save the index of a list item

Basically, how could I insert an element into a list at a specific position? For example, in the following, I remove a random element from a set and add it back in, but not in order. I know I can use bisect.insort for numbers, but what if I were using strings? Example:

>>> a = ['one', 'two', 'three', 'four', 'five']
>>> import random
>>> b = random.choice(a)
>>> a.remove(b)
>>> a
['one', 'two', 'four', 'five']
>>> b
'three'
>>> a += [b]
>>> a
['one', 'two', 'four', 'five', 'three']

I want to be able to place something back in at a specific location.

Upvotes: 1

Views: 6305

Answers (1)

thumbtackthief
thumbtackthief

Reputation: 6211

If you know the index(position) of the element you want to enter, the command list.insert(index,item) will do what you want.

>>>numbers = ['one', 'two', 'three', 'four', 'five']
>>>import random
>>>removed = random.choice(numbers)
>>>index = numbers.index(removed)
>>>numbers.remove(removed)
>>>numbers.insert(index, removed)
['one', 'two', 'three', 'four', 'five']

https://docs.python.org/2/tutorial/datastructures.html

Upvotes: 3

Related Questions