How to move all items one item forward in a list

Question:

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:

['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!

Asked By: Xpray 935

||

Answers:

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']
Answered By: Branson Smith

You can insert the item into the desired position, and then remove the last item.

Here is the code:

# Starting list
x = ['Hello', "Hi", 'Nice', 'Cool']

items_to_insert = 'Love'
item_to_find = "Hi"

if item_to_find in x:
    x.insert( x.index(item_to_find), items_to_insert)
    x.pop()
    print(x)
else:
    print(f"{item_to_find} is not in the list")

OUTPUT:

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

Working with integers in the list:

x = ['Hello', 6, 'Nice', 'Cool']

items_to_insert = 'Love'
item_to_find = 6

if item_to_find in x:
    x.insert( x.index(item_to_find), items_to_insert)
    x.pop()
    print(x)
else:
    print(f"{item_to_find} is not in the list")

OUTPUT:

['Hello', 'Love', 6, 'Nice']
Answered By: ScottC
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.