0

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']
2
  • 1
    The integer 5 or the string '5'? Commented Oct 20, 2020 at 13:15
  • @schwobaseggl oh ok removing dupe. Commented Oct 20, 2020 at 13:26

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.