Python List Types Reference

Quick reference to the list types of Python.

List Operations
Operation Example
Concatenation [1, 2, 3] + [4, 5, 6]
Iteration for x in [1, 2, 3]: print x
Length len([1, 2, 3])
Membership 3 in [1, 2, 3]
Repetition ['Hi!'] * 4
List Functions
Function Does what
cmp(list1, list2) Compares elements of both lists.
len(list) Returns the total length of the list.
list(seq) Converts a tuple into a list.
max(list) Returns the item with maximum value from the list.
min(list) Returns the item with minium value from the list.
List Methods
Method Does what
list.append(obj) Appends object obj to list.
list.count(obj) Returns count of how many times obj occurs in list.
list.extend(seq) Appends the contents of seq to list.
list.index(obj) Returns the lowest index in list that obj appears.
list.insert(index, obj) Inserts object obj into list at offset index.
list.pop(obj=list[-1]) Removes and returns last object or obj from list.
list.remove(obj) Removes object obj from list.
list.reverse() Reverses objects of list in place.
list.sort([func]) Sorts objects of list, use compare func if given.
Tuples Operations
Operation Example
Concatenation (1, 2, 3) + (4, 5, 6)
Iteration for x in (1, 2, 3): print x
Length len((1, 2, 3))
Membership 3 in (1, 2, 3)
Repetition ('Hi!',) * 4
Tuples Functions
Function Does what
cmp(tuple1, tuple2) Compares elements of both tuples.
len(tuple) Returns the total length of the tuple.
max(tuple) Returns the item with maximum value from the tuple.
min(tuple) Returns item with minimum value from the tuple.
tuple(seq) Converts a list into a tuple.
Dictionary Functions
Function Does what
cmp(dict1, dict2) Compares elements of both dictionaries.
len(dict) Returns the total length of the dictionary. This would be equal to the number of items in the dictionary.
str(dict) Produces a printable string representation of a dictionary.
type(variable) Returns the type of the passed variable. If variable is a dictionary it returns the dictionary type.
Dictionary Methods
Method Does what
dict.clear() Removes all elements of dictionary dict.
dict.copy() Returns a shallow copy of dictionary dict.
dict.fromkeys(sequence [, value]) Creates a new dictionary with keys from sequence and values set to value.
dict.get(key, default=None) Returns value for key key or default if key is not in dictionary.
dict.has_key(key) Returns True if key is in dictionary dict, false otherwise.
dict.items() Returns a list of dictionary dict's (key, value) tuple pairs.
dict.keys() Returns a list of dictionary dict's keys.
dict.setdefault(key, default=None) Similar to get(), but will set dict[key]=default if key is not already in dict.
dict.update(dict2) Adds dictionary dict2's key-values pairs to dict.
dict.values() Returns a list of dictionary dict's values.

More: