Python - List List methods

Introduction

reverse method reverses the list in-place.

The extend and pop methods insert multiple items at and delete an item from the end of the list, respectively.

There is a reversed built-in function that works much like sorted and returns a new result object.

It must be wrapped in a list call in both 2.X and 3.X here because its result is an iterator that produces results on demand:

Demo

L = [1, 2] 
L.extend([3, 4, 5])              # Add many items at end (like in-place +) 
print( L )
print( L.pop() )                         # Delete and return last item (by default: -1) 
print( L )
L.reverse()                      # In-place reversal method 
print( L )
print( list(reversed(L)) )               # Reversal built-in with a result (iterator)
# from   www .  j  av a 2 s  .  c  o m

Result

extend method adds many items, and append method adds one.

The list pop method is often used in conjunction with append to implement a quick last-in-first-out (LIFO) stack structure.

Demo

L = [] 
L.append(1)                      # Push onto stack 
L.append(2) # from w w w.j a v a 2  s. c  om
print( L )
print( L.pop() )                          # Pop off stack 
print( L )

Result

The pop method accepts an optional offset of the item to be deleted and returned. The default is the last item at offset -1.

More method demonstration:

Demo

L = ['test','eggs', 'ham'] 
print( L.index('eggs') )                  # Index of an object (search/find) 
L.insert(1, 'toast')             # Insert at position 
print( L )
L.remove('eggs')                 # Delete by value 
print( L )
print( L.pop(1) )                         # Delete by position 
print( L )
L.count('test')                  # Number of occurrences
#  w  w w .j  ava 2 s  .  com

Result

Related Topic