October 10, 2024
aws
Python Loop over List and swap elements
Swap elements in a list of any size
- assign length variable with the current list's length for convenience
- for loop runs through body
length // 2times, to leave middle element of odd lists untouched - swap the
ith element with the element equal to(length - i) - 1 - i.e. when i is element
0the swap is with element4-->(length - 0) - 1
my_list = [10, 1, 8, 3, 5] length = len(my_list) for i in range(length // 2) my_list[i], my_list[length - i - 1] = my_list[length - i - 1], my_list[i] print(my_list)
Loading comments...