pop item from list python code example

Example 1: remove element from list

>>> a = [0, 2, 3, 2]
>>> a.remove(2)
>>> a
[0, 3, 2]

Example 2: python pop element

my_list = [123, 'Add', 'Grepper', 'Answer']
my_list.pop()
-->[123, 'Add', 'Grepper'] #last element is removed

my_list = [123, 'Add', 'Grepper', 'Answer']
my_list.pop(0)
-->['Add', 'Grepper', 'Answer'] #first element is removed

my_list = [123, 'Add', 'Grepper', 'Answer']
any_index_of_the_list = 2
my_list.pop(any_index_of_the_list)
-->[123, 'Add', 'Answer'] #element at index 2 is removed 
						  #(first element is 0)

Example 3: python pop

# Python list method pop() removes
# and returns last object or obj from the list.
# .pop() last element .pop(0) first element

my_list = [123, 'Add', 'Grepper', 'Answer'];
print "Pop default: ", my_list.pop()
> Pop default:  Answer
# List updated to [123, 'Add', 'Grepper']
print "Pop index: ", my_list.pop(1)
> Pop index: Add
# List updated to [123, 'Grepper']

Example 4: how to pop things out of list python

>>> l = ['a', 'b', 'c', 'd']
>>> l.pop(0)
'a'
>>> l
['b', 'c', 'd']

Example 5: python remove

# the list.remove(object) method takes one argument 
# the object or element value you want to remove from the list
# it removes the first coccurence from the list

generic_list = [1, 2, 2, 2, 3, 3, 4, 5, 5, 5, 6, 8, 8, 8]

generic_list.remove(1)

# The Generic list will now be:
# [2, 2, 2, 3, 3, 4, 5, 5, 5, 6, 8, 8, 8]

Example 6: pop list python

#pop removes the last element
li=[1,2,3,4,5]
li.pop()
#>>>[1, 2, 3, 4]

Tags:

Misc Example