Reputation: 11
I am trying to make a new list, which is a replica of an other list. This new list I want to modify by changing values at specific positions.
I found this question, and the most upvoted answer can make a new list and add on to the old list. This is a good start, but I want to decide where the additions are done (in his version, it just adds it on to the end of the list)
What he has:
myList = [10,20,30]
yourList = myList + [40]
print("your list: " + yourList)
your list: [10,20,30,40]
In this instance, I would want to be able to change where the 40 in your list goes ie
your list: [10,40,20,30]
I'm unsure how I would go about doing that. Thanks! (Pretty new here sorry if I'm not clear)
Upvotes: 1
Views: 1628
Reputation: 631
you can copy your list and insert the value in the new list something like this:
my_list = [1,2,3,4,5,6]
my_2_list = my_list.copy()
then i wnat to insert a vlue at position 3 i can do
my_2_list.insert(3, value)
Upvotes: 0
Reputation: 155418
Use slicing to split the original list apart at the desired index, then put it back together again.
For example:
insert_at = 1
myList = [10,20,30]
# Uses PEP 448 unpacking generalizations to avoid excess temporary `list`s
yourList = [*myList[:insert_at], 40, *my_list[insert_at:]]
# Or via concatenation (involves an extra temporary)
yourList = myList[:insert_at] + [40] + my_list[insert_at:]
print("your list: " + yourList)
Alternatively, if you don't need a one-liner, copy the list
, then call insert
on the copy:
yourList = myList[:] # myList.copy() also works on Python 3
yourList.insert(insert_at, 40)
Upvotes: 1
Reputation: 21275
To keep the same list:
Use the insert
method of the list
class
myList.insert(1, 40)
insert(index, element)
inserts the element
into the list at the position index
- shifting the remaining elements rightward as required.
To make a new list:
new_list = myList.copy()
new_list.insert(1, 40)
Upvotes: 0