Python - Data Type List Operations

Introduction

Python's lists are like arrays in other languages but more powerful.

List has no fixed type constraint.

Lists have no fixed size. They can grow and shrink on demand:

Demo

L = [123, 'test', 1.23]            # A list of three different-type objects 
#  w  w  w  . j a  v a 2  s  . c om
L.append('NI')                     # Growing: add object at end of list 
print( L )

print( L.pop(2) )                           # Shrinking: delete an item in the middle 
print( L )                                  # "del L[2]" deletes from a list too

Result

Here, the list append method expands the list's size and inserts an item at the end.

The pop method or an equivalent del statement then removes an item at a given offset, causing the list to shrink.

Demo

M = ['bb', 'aa', 'cc'] 
M.sort() #  ww  w. j a  v a2  s . co  m
print( M )
M.reverse() 
print( M )

Result

The list sort method orders the list in ascending fashion by default, and reverse reverses it-in both cases, the methods modify the list directly.

Related Topic