-2

I want to swap the consecutive elements of a list such that the first element will go to the last. eg [4, 7, 3, 4, 3] should print as [7,3,4,3,4] This is the code I've written but it doesn't work right. How can I modify it to get it working?

ls = [4, 7, 3, 4, 3]
i=0
b=1
while i+1<len(ls):
    ls[i]=a
    ls[i]=ls[i+1]
    ls[i+1]=a
    i+=1
print ls

I do not want to just switch the first element with the last one. I want to modify this code further to create a bubble sort algorithm, I am just confused at how to get done what I just explained.

Updated : Thanks for the answer that I should change "ls[i]=a" with "a=ls[i]", but can someone explain to me how this differs in logic?

Hammad Manzoor
  • 144
  • 1
  • 11

3 Answers3

4

You don't need a loop to move the first element to the last. Just pop the first element off the list, then append it.

ls.append(ls.pop(0))
kindall
  • 178,883
  • 35
  • 278
  • 309
2

Python allows to work with lists by selecting one or several elements at the time and to concatenate the content of the list

ls = [4, 7, 3, 4, 3]
new_list_with_first_element_at_the_end = ls[1:] + [ls[0]]
Guillaume Jacquenot
  • 11,217
  • 6
  • 43
  • 49
1

If you really feel you must, make a swap function:

def swap(l, i, j):
    tmp = l[j]
    l[j] = i
    l[i] = tmp

Then you can:

for i in range(len(l)-1):
     swap(l, i, i+1)
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96