Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I swap two elements in one array? [duplicate]

I have an array like :

a=np.array([2,7])

a=[2,7]

and I want to swap the same array like 7,2 is there anyway to do?

answer should be like 7,2

a=[7,2]
like image 206
Radhe Avatar asked May 12 '26 18:05

Radhe


2 Answers

#a=np.array([2,7]) 
a=[2,7]

# Reversing a list using slice notation
print (a[::-1]) # [7, 2]

# The reversed() method
print (list(reversed(a))) # [7, 2]

swap two elements in a list:

# Swap function
def swapPositions(list, pos1, pos2):
    list[pos1], list[pos2] = list[pos2], list[pos1]
    return list


a=[2,7]
pos1, pos2 = 0, 1

print(swapPositions(a, pos1 - 1, pos2 - 1))
like image 118
ncica Avatar answered May 15 '26 07:05

ncica


Try np.flip(a,0) See this for more information.

like image 28
Abhishek S Avatar answered May 15 '26 06:05

Abhishek S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!