Home > Back-end >  Removing an element from a list by index without returning the deleted element
Removing an element from a list by index without returning the deleted element

Time:04-07

simply put, I just want an alternative to .pop that does not return the removed element and also takes an index for parameters. To give an example, I enter this code:

[1, 2, 3].pop(0)

but it gives me this as an output:

[1]

what I want as an output is [2, 3] and not [1]. is there a simple way of doing this?

CodePudding user response:

If you store the list [1, 2, 3] inside a variable say test, apply pop on that variable and then print the variable you would get the desired results

test = [1, 2, 3]
test.pop(0)
print(test)

Output -

[2, 3]

CodePudding user response:

you should use the remove() method but it takes an element as an argument not an index if you want to use an index try this

test = [1, 2, 3]
test.remove(test[0])

the output should be [2, 3]

CodePudding user response:

You can also use list slicing method.

print([1,2,3][1:])

CodePudding user response:

del command is what you're looking for. For more information: https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types

a = [1, 2, 3]
del a[0]
print(a)

CodePudding user response:

You can override defination of pop or create a user defined function, something like below.

def pop_and_remove(index, arr):
    arr.pop(index)
    return arr

Now call pop_and_remove(0, arr) this will return updated arr.

  • Related