rem
rem

Reputation: 31

Move an element in a list

If a list has elements like

 [A, B, C, ., D] 

How would I get C to move into the empty space to the right of it? I know I would first have to look and see if there is an period next to a character. What I am having trouble with is the moving part. I want to move C and move the period in it's old spot.

Upvotes: 0

Views: 10097

Answers (3)

vribeiro
vribeiro

Reputation: 161

You mean, like, changing C and the dot position? You could have something like:

list_ = [A, B, C, ., D]
list_[2], list_[3] = list_[3], list_[2]

The list_ would look like [A, B, ., C, D].

Upvotes: 3

Def_Os
Def_Os

Reputation: 5467

my_list = ['A', 'B', 'C', '.', 'D']
old_index = my_list.index('.')
# Pop out the '.' and insert into the preceding index.
my_list.insert(old_index - 1, my_list.pop(old_index))
print(my_list)

> ['A', 'B', '.', 'C', 'D']

Upvotes: 1

Francisco
Francisco

Reputation: 11476

You first have to find the position of the element you want to swap, and then you can swap it like this:

>>> l = ["A", "B", "C", ".", "D"]
>>> c_i = l.index("C")
>>> l[c_i], l[c_i+1] = l[c_i+1], l[c_i]
>>> l
['A', 'B', '.', 'C', 'D']

Upvotes: 2

Related Questions