Python List Object

Overview

  • Ordered collection of other objects(numbers, strings, and even other lists);
  • List is mutable object and can be changed in place, can grow and shrink on demand. And may contain and be nested in any other objects;
  • Fetching an item from Python list is as fast as indexing a C array;
  • Sequence operations like concatenation and slicing return new lists instead of new strings;

List Operations

'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'

1.List supports "+" and "*" operations like strings:

>>> ['a','b','c'] + [1, 2, 3]
['a', 'b', 'c', 1, 2, 3]
>>> ['Hi!'] * 5
['Hi!', 'Hi!', 'Hi!', 'Hi!', 'Hi!']
>>> list('hello') + list('world')
['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']

2.Membership testing

>>> 'a' in ['a','b','c']
True  
>>> 'x' in ['a','b','c']
False  

3.Indexing, Slicing, and Matrixes

>>> matrix = [[1,2,3],[4,5,6],[7,8,9]]
>>> matrix
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> matrix[0][0]
1  
>>> matrix[0]
[1, 2, 3]

4.Changing Lists in Place

>>> List = ['a','b','c']
>>> List[1] = 'x'    # Change the seconde element value
>>> List
['a', 'x', 'c']
>>> List[0:2] = ['A','B']  # replaces an entire subset of a list in a single step 
>>> List
['A', 'B', 'c']

5.Sorting

>>> m1 = ['d','c','b', 'a']
>>> m1.sort()      # sort function will change the list in place
>>> m1
['a', 'b', 'c', 'd']
>>> m1.sort(reverse=True)  # sort element by descending order
>>> m1
['d', 'c', 'b', 'a']

6.Other built-in functions

>>> m2 = []
>>> m2.append('item1') # append new element to the end
>>> m2
['item1']
>>> m2.insert(0,'item0')  # insert to specified position
>>> m2
['item0', 'item1']
>>> m3 = m2.copy()  # make a top-level copy
>>> m3 == m2
True  
>>> m3 is m2
False  
>>> m2.extend(['item2','item3'])
>>> m2
['item0', 'item1', 'item2', 'item3']
>>> m2.pop()        # pop out last element from list
'item3'  
>>> m2.count('item3') 
0  
>>> m2.count('item1')
1  
>>> m2.index('item2')  # return element's index value
2  
>>> del m2[0]    # use del statement to delete an item
>>> m2
['item1', 'item2'] 
>>> m2.remove('item2')  # remove element
>>> m2
['item1']
>>> m2.clear()   # clear all items
>>> m2
[]