Reputation: 25
Writing a simple code to print a random list, the swap the first position integer with the last position integer and re-print the list. Keep getting error saying not subscriptable. This is for a basic python class but we are on Thanksgiving break and can't talk to professor, due when we get back.
import random
def main():
mylist=[]
for i in range(15):
mylist.append(random.randrange(0,25))
print(mylist)
def swap():
a, b = mylist.index[0], mylist.index[14]
mylist[b], mylist[a] = mylist[a], mylist[b]
print(mylist)
swap()
main()
Upvotes: 2
Views: 713
Reputation: 6573
You are swapping with indexes equal to the values in the list (instead of indexes).
Try:
mylist[0], mylist[-1] = mylist[-1], mylist[0]
On another observation, I believe you have to pass mylist to swap
as a parameter. (unless swap is defined in main).
Upvotes: 1
Reputation: 273
You need to hold one of the values in a variable and then swap.
def swap():
x = mylist[0]
mylist[0] = mylist[14]
mylist[14] = x
print(mylist)
Upvotes: 3