Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to move all items one item forward in a list

I’m trying to do the following (consider this list):

['Hello, 'Hi', 'Nice', Cool']

I would like to change ‘Hi’ to ‘Love’

But, I wouldn’t want it to stay that way:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

['Hello, 'Love', 'Nice', Cool']

I’m trying to get ahead of the others, even cropping the last one, getting like this:

['Hello, 'Love', 'Hi', Nice']

Note that Hi passed one along with the entire list, that’s what I want!

Anybody know? Thanks in advance!

>Solution :

old_list = ['Hello', 'Hi', 'Nice', 'Cool']
new_item_index = 1
new_item = 'Love'

new_list = old_list[0:new_item_index] + [new_item] + old_list[new_item_index+1:]
print(old_list)
print(new_list)
['Hello', 'Hi', 'Nice', 'Cool']
['Hello', 'Love', 'Hi', 'Nice']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading