I'd like to move multiple items from one list to another.
The items are to be removed from the first list and inserted at the end of the second list.
The value of the items are unknown but the indexes of the items are known.
I'd like to do so in one line of code.
The code below does what I'd like but not in one line of code:
listOne = [0, 1, 2, 3, 4, 5]
listTwo = [6, 7, 8, 9, 10]
listTwo = listTwo listOne[0:2]
listOne = listOne[2:]
Is there a clean way to do so using functions (such as pop(), inser() etc.) in conjunction with each other?
CodePudding user response:
You can make something like that
listOne = [0, 1, 2, 3, 4, 5]
listTwo = [6, 7, 8, 9, 10]
# Must respect this criteria : 0 <= X < Y <= len(listOne)
Y = 2
X = 0
listTwo.extend([listOne.pop(X) for _ in range(Y-X)])
print(listTwo) # [6, 7, 8, 9, 10, 0, 1]
print(listOne) # [2, 3, 4, 5]
Correction based on the jarmod comment
CodePudding user response:
You can put your solution itself on one line -
listOne = [0, 1, 2, 3, 4, 5]
listTwo = [6, 7, 8, 9, 10]
listTwo, listOne = listTwo listOne[0:2], listOne[2:]
print(listTwo)
# [6, 7, 8, 9, 10, 0, 1]
print(listOne)
# [2, 3, 4, 5]
CodePudding user response:
You can achieve this with 2 easy "for" loops where in the first one you append all the elements from the first list to the second and than empty out all the elements in L1
listOne = [0, 1, 2, 3, 4, 5]
listTwo = [6, 7, 8, 9, 10]
# Append all the elements from the first list to the second
for element in listOne:
listTwo.append(element)
# Empty out the first list whose elements are already added in l2
for el in range(len(listOne)):
listOne.pop(0)
print(listOne)
print(listTwo)
The output would provide you with listTwo who has all the elements and listOne which has none
[6, 7, 8, 9, 10, 0, 1, 2, 3, 4, 5]
[]