Home > Back-end >  How to insert elements at a specific index in a list and return the updated list
How to insert elements at a specific index in a list and return the updated list

Time:09-21

Let's say I got a list below:

original = ['a', 'c', 'e']

I want to add another list, called add_item, to the list original:

add_item = ['b', 'd']

The result should be:

['a', 'b', 'c', 'e']

What is the syntactically cleanest way to accomplish this?

Thanks for any help!!

CodePudding user response:

original = ['a', 'c', 'e']
add_item = ['b', 'd']
original.extend(add_item) #['a', 'c', 'e', 'b', 'd']

CodePudding user response:

original = ['a', 'c', 'e']
add_item = ['b', 'd']

print(sorted(original   add_item))

You can use the overloaded operator to concatenate lists, and if sorting is important to you you can use the built-in sorted function

CodePudding user response:

Syntactically the cleanest way would be to use extend method

original = ['a','c','e']
original.extend(add_item)

  • Related