Reputation: 31
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
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
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
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