Reputation: 19
I'm new to programming and I'm learning Python. I have to make a function that will swap 2 indices within a list. The list is given but the indices to be swapped need to be input by the user. So far I've been able to come up with this...
def listSwap():
print("This program will swap two indices within a list")
myList = [3, 4, 2, 5, 1, 14, 23, 1]
print("Here is your list... ", myList)
index1 = eval(input("Pick an index from the list you would like to swap... "))
index2 = eval(input("Now pick another index to swap with the first... "))
tempIndex = index1
myList[index1] = myList[index2]
myList[index2] = myList[tempIndex]
print("Here is your new list with swapped indices", myList)
def main():
listSwap()
main()
but it doesn't work like I need it to. It will swap 1 index but not the other. Could I get some help? Maybe explain what I'm doing wrong?
Upvotes: 1
Views: 283
Reputation: 146
You're not swapping "indexes" here, you're swapping the values stored in the array, de-referenced using the index. Given a list:
a = [1, 2, 5, 3]
print(a[0])
prints "1". When you do:
a[0] = a[1]
you are replacing the value at a[0]
with the value at a[1]
, losing the value at a[0]
. You will now have a = [2, 2, 5, 3]
.
What you're trying to achieve is to swap numbers at position 0
and 1
. To do this, you need to make a copy of the value at a[0]
so you don't lose it when you write over it with a[1]
.
Do this:
a = [1, 2, 5, 3]
index1 = 0
index2 = 1
temp = a[index1] # stores "1" in temp
a[index1] = a[index2] # changes a to [2, 2, 5, 3] by replacing a[0] with value in a[1]
a[index2] = temp # stores "1" inside temp into a[1], changing a to [2, 1, 5, 3]
This is a common problem, related to reference vs value.
Upvotes: 0
Reputation: 3352
def your_swap(the_list, A, B):
assert A > 0 and A < len(the_list)
assert B > 0 and B < len(the_list)
if A == B: return the_list
object_at_position_A = the_list[A]
the_list[A] = the_list[B]
the_list[B] = object_at_position_A
return the_list
Upvotes: 0
Reputation: 160427
First, do not use eval
, it is not recommended.
Instead, use:
index1 = int(input("Pick an index from the list you would like to swap... "))
index2 = int(input("Now pick another index to swap with the first... "))
Secondly there is no need to temporarily save the index value, just the list item with that index:
index_value_1 = MyList[index1]
And then perform the switch.
myList[index1] = myList[index2]
myList[index2] = index_value_1
Upvotes: 1
Reputation: 34281
The problem is that your code essentially equals to:
myList[index1] = myList[index2]
myList[index2] = myList[index1]
and the usage of the third 'temporary' variable for the index does not help. A correct version with a temp variable would look like:
temp = myList[index1]
myList[index1] = myList[index2]
myList[index2] = temp
But, luckily, Python has more elegant way of swapping values:
myList[index1], myList[index2] = myList[index2], myList[index1]
Upvotes: 7