简体   繁体   中英

How to remove specific elements from python list and add those elements into last of the list?

There are many solution available on internet for the above question but i am building my own logic here and have written below solution so far but my code is not dynamic eg my code is only working for num = 2.

How can we write code for dynamic user input using below logic. Any suggestion will be appreciated.

My Code:

l = [1,2,3,4,5,6,7]
l1 = []

num = 2

print('original list is:', l)

for i in range(0,num-1):
    rem = l.pop(i)
    l1.append(rem)

for i in range(0,num-1):
    rem = l.pop(i)
    l1.append(rem)

print('poup list is',l1)

l.extend(l1)
print('reverse list is',l)

My Output: (when num = 2)

original list is: [1, 2, 3, 4, 5, 6, 7]
poup list is [1, 2]
reverse list is [3, 4, 5, 6, 7, 1, 2]

My Output: (when num = 3)

original list is: [1, 2, 3, 4, 5, 6, 7]
poup list is [1, 3, 2, 5]
reverse list is [4, 6, 7, 1, 3, 2, 5]

Expected Solution:

l = [1,2,3,4,5,6,7]

num = 2 (This number can be dynamic, User can pass any number)

Output: l = [3,4,5,6,7,1,2]

If user passed num = 3 then output should be like below:

Output: l = [4,5,6,7,1,2,3]

Even though the poup list and reverse list doesn't seem to represent the lists with the best names, the following code snippet should solve your problem:

l = [1,2,3,4,5,6,7]
print("Original list: {}".format(l) )
num = input("Enter value of 'num': " )

l1 = []
for i in range(0,int(num)):
    rem = l.pop(0)
    l1.append(rem)
    
print('poup list is',l1)
l.extend(l1)
print('reverse list is',l)

Here num is dynamically stored. The only minor correction to your for loop is that l should always pop the first element. This is because once an element is popped, the second element becomes the first element of your list. But due to incrementation in the value of i , it just skips that element.

Here's a sample output:

Original list: [1, 2, 3, 4, 5, 6, 7]
Enter value of 'num': 4
poup list is [1, 2, 3, 4]
reverse list is [5, 6, 7, 1, 2, 3, 4]
​

You could use a while loop. Problem with your code is that index positions changed when popping, in case of num = 2 it was fine, but then it messed up with new positions.

l = [1,2,3,4,5,6,7]
l1 = []

num = 3

print('original list is:', l)

y = 0
while y != num:
    rem = l.pop(0)
    y +=1
    l1.append(rem)
    print(l)


print('poup list is',l1)

l.extend(l1)
print('reverse list is',l)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM