Ta101
Ta101

Reputation: 11

inserting integer at each index of python list

How would I insert integer '5' at each index of following list an element in new list per index

I have a list

['2', '6', '8']

and would like to insert '5' in following way:

['5', '2', '6', '8']
['2', '5', '6', '8']
['2', '6', '5', '8']
['2', '6', '8', '5']

Upvotes: 0

Views: 53

Answers (1)

tobias_k
tobias_k

Reputation: 82889

You could use a list comprehension using slices of the list to and from each index:

>>> lst = ['2', '6', '8']
>>> [lst[:i] + ["5"] + lst[i:] for i in range(len(lst)+1)]
[['5', '2', '6', '8'],
 ['2', '5', '6', '8'],
 ['2', '6', '5', '8'],
 ['2', '6', '8', '5']]

Or using *-unpacking, same result: [[*lst[:i], "5", *lst[i:]] for ...]. Both versions create a bunch of temporary list slices. The alternative would be to use a loop, make a copy of the list, and then calling insert; both approaches should have ~O(2n) per list, so it does not really make a difference.

Upvotes: 5

Related Questions