Hello, everyone
I'm inquiring because it couldn't be solved while working with Python
For example,
When there is a list a and b,
a=[1,2,3,4,5]
b=[6,7,8,9,10]
Backside
Could you help me with how two lists can exchange elements from one point to another?
ex) (Exchange from first to fourth elements)
a=[6,7,8,9,5] b=[1,2,3,4,10] I'm asking you this!
I'm asking you this question because I think there's a way to change the list instead of making a new one!
Thank you!
python
Hello! If the length of the list is the same, I think we can do this
Tie it with a zip,
Get index value with enumerate.
Swapped with a, b = b, a.
a=[1,2,3,4,5]
b=[6,7,8,9,10]
def change(num):
for i, (l, m) in enumerate(zip(a,b)):
a[i], b[i] = m, l
if i == num-1:
break
change(3)
print(a, b)
# # a = [6, 7, 8, 4, 5]
# # b = [1, 2, 3, 9, 10]
Have a nice day.
Swap in Python is simple.
Look at the example below and do it yourself.
a = [1,2,3,4,5]
b = [6,7,8,9,10]
a[0], b[0] = b[0], a[0]
# # a -> [6, 2, 3, 4, 5]
# # b -> [1, 7, 8, 9, 10]
a[0], b[0], a[1], b[1] = b[0], a[0], b[1], a[1]
# # a -> [6, 7, 3, 4, 5]
# # b -> [1, 2, 8, 9, 10]
© 2024 OneMinuteCode. All rights reserved.