How can we move an element on a list in Python? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 9

How can we move an element on a list in Python?

So say I have a list list = [1,2,3,4,5] how can I move say "2" so that I have list = [1,3,4,2,5] or list = [1,3,4,5,2] or anywhere I like with having the element still ordered? Is there a fast way so I have all the possibilites so that 2 is moved with the element still ordered? Thank you

20th Jun 2018, 9:12 PM
Muhammad Hasan
Muhammad Hasan - avatar
9 Answers
+ 12
Muhammad Hasan Ok then: lst = [1, 2, 3, 4, 5] print(lst) lst.insert(2, lst.pop(1)) print(lst) >>> [1, 2, 3, 4, 5] [1, 3, 2, 4, 5]
20th Jun 2018, 9:41 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 9
You could also swap list elements with: lst[i], lst[j] = lst[j], lst[i] e.g., lst = [1, 2, 3, 4, 5] print(lst) lst[1], lst[2] = lst[2], lst[1] print(lst) >>> [1, 2, 3, 4, 5] [1, 3, 2, 4, 5]
20th Jun 2018, 9:59 PM
David Ashton
David Ashton - avatar
+ 9
After learning about itertools and finding motivation I finally found a way to have all the possibility 😅 Thank you for helping me Kuba Siekierzyński https://code.sololearn.com/cUh6113vl0tv/?ref=app
21st Jun 2018, 1:27 AM
Muhammad Hasan
Muhammad Hasan - avatar
+ 6
First of all, the above is not a list, but a set, which is an unordered collection. List is made with square brackets. Then: lst = [1, 2, 3, 4, 5] print(lst) lst.append(lst.pop(1)) print(lst) >>> [1, 2, 3, 4, 5] [1, 3, 4, 5, 2]
20th Jun 2018, 9:32 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 6
Muhammad Hasan If you want to have all possible permutations, just go: from itertools import permutations print(list(permutations(lst))) And refer to the third lesson here: https://www.sololearn.com/learn/JUMP_LINK__&&__Python__&&__JUMP_LINK/2466
20th Jun 2018, 10:15 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 5
Kuba Siekierzyński Oopss... I accidentally put brackects 😅 Hmm nice answer... but I think that only works If I want to put it in the end... I need it to be anywhere that I want..🤔
20th Jun 2018, 9:38 PM
Muhammad Hasan
Muhammad Hasan - avatar
+ 5
David Ashton Yeah, I've thought of that too, but I think it's not an ideal solution It only works if I swap 2 with 3, if I swap 2 with 4 then it wouldn't be ordered as I want
20th Jun 2018, 10:04 PM
Muhammad Hasan
Muhammad Hasan - avatar
+ 5
So to get all the possibilities do I have to do this manually .__. ? Kuba Siekierzyński
20th Jun 2018, 10:05 PM
Muhammad Hasan
Muhammad Hasan - avatar
+ 4
Thank you all, sorry for being such a newbie I have learnt how to permutate and use itertools, but it's hard to implement on this, maybe I'll try learning more about itertools Other answers are still needed
20th Jun 2018, 10:21 PM
Muhammad Hasan
Muhammad Hasan - avatar