Reputation: 11
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
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