User Tools

Site Tools



last update: 09.06.2011

What are they?

List: simply an ordered collection of objects. Object can have any legal Python name and a list can grow dynamically. Lists are ordered sequence type. A index can be used for accessing elements.

Tuple: is similar to a list, but it's a read-only version. The items cannot be added or removed from a tuple.

Dictionary: unordered collection of objects pairs (key ⇒ value)


Defining a list is just an assignment to a variable using = operator. The list is enclosed in square brackets.

list_numerical = [12, 35, 64, 4]
list_string	= ["Joe", "Mary", "Zoro"]
list_sublist = ["Python", "PHP", ["Another list", 2344]]

The items in a list can accessed by an zero-based index, means that first element is list[0], the next list[1] and so on. If you want to access the last element, you can use negative index, list[-1]. For the previous item, list[-2] and so on.

Slice: a subset of a list. You can obtain a slice by referencing a list using a starting index and a ending index, separated by a colon (:).

days_list = ["Maandag", "Dinsdag", "Woensdag", \
		"Donderdag", "Vrijdag", "Zaterdag", "Zondag"]
items_count = len(days_list)
slice = days_list[ : 4] -> returns ['Maandag', 'Dinsdag', 'Woensdag', 'Donderdag']
slice = days_list[-5 : -2] -> returns ['Woensdag', 'Donderdag', 'Vrijdag']

Adding/Removing elements


	listname.append("elem") -> adds to the end of the list
	listname.insert(2, "Element") -> adds "Element" at index 2
	listname.extend(anotherlist) -> accepts only a list; add multiple elem
						 	at the same time
	list1 += list2 -> similar to extend


	listname.pop(index) -> remove an item by its index and then returns it
	listname.remove(item) -> search the list and remove the first occurrence.

Sorting a list


Sorts the list based on the total value of each object. It modifies the order of the objects in the list itself.

Sort() method can accept a comparison function as an argument. This function can accept two arguments and must return -1, 0, 1 depending on whether the first arg is smaller, equal or greater than the second one.

weekdays_list.sort(lambda x, y: some_function(x, y))

Sort() method can also accept a key function. This key function should accept one argument that will be used to extract a key from each object from the list. The list will be then ordered by this extracted key.

weekdays_list.reverse()=weekdays_list.sort(reverse=1) -> sorting in reverse order
	reverse() - just reverses the string w/out any alteration


They cannot be modified after initial declaration. They use parentheses.

tuple_vegetables = ('melon', 'carrot', 'potato')

the data is immutable (static)
faster access than a list

NOTE: the tuple constructor is the comma, not the parentheses! (but we use them for clarity). For example:

a = 1,2
<type 'tuple'>

Transforming tuple → list using function list(). Reverse: tuple().

list_numbers = [2, 5, 4, 6]
tuple_numbers = tuple(list_numbers)
list_again = list(tuple_numbers)


Assign a value or a group of values to a key. The keys must be integers, string or immutable tuple (made up of strings or/and integers).

Defining dictionaries:

some_dict = { 'one' : 1, 'two' : 2, 'three' }
another_dict = dict(
    one = 1, two = 2,
    three = 3

Note: the dict() method accepts only strings that are valid identifiers (variable names) to be mapped. So, a dict(1 = one) will not work.

Dictionaries types:

  1. one to one - key to value association

dict_numbers = { 1 : 'one', 2 : 'two', 3 : 'three' }

  1. one to many - can be accomplished using list objects as values

dict_numbers = { 1 : ['one', 'two', 'three'], 2 : ['four', 'five'] }

  1. many to many - can be accomplished using tuples as keys, lists as values
tuple_as_key_1 = (1, 2, 3, 4, 5)
tuple_as_key_2 = (4, 6, 7)
set_dict = {tuple_as_key_1 : ['sd', 'ff'], tuple_as_key_2 : ['sd', 'fd']}

=> {(1, 2, 3, 4, 5): ['sd', 'ff'], (4, 6, 7): ['sd', 'fd']}

Adding a value = setup a key to correspond to a value - if already exists, replace the key value, otherwise just add the pair key,value to the dictionary Keys are case-sensitive (Key is not key).

Retrieving a value

dict_example = { 1 : 'one', 2 : 'two', 'key' : 3}
dict_example.keys() => [1, 2, 'key']
dict_example.values() => ['one', 'two', 3]
dict_example.items() => [(1, 'one'), (2, 'two'), ('key', 3)]
dict_example[2] => two
dict_example.get(12, 43) # use this to prevent unexisting key to throw an error

Slicing a dictionary

No specific method: just retrieve all keys, make some slicing using the keys list, and then in a for cycle retrieve (get or pop) the values from the dictionary for sliced keys.

Swaping keys - values in a dictionary

intial_dict = { 1 : 'one', 2 : 'two', 'key' : 3}
swapped_dict = {}
for key, val in intial_dict.iteritems():
	swapped_dict[val] = key

Sorting after keys/values

sorted(dict.keys()) # or simply sorted(dict)

Iterate over a dictionary

for key in dictionary.iterkeys():
    print key, dictionary[key]
for key in dictionary.keys():
    print key, dictionary[key]
for key, value in dictionary.items():
    print key, value

Looking for a value/key

# look for a known value and return the key
return [ k for k,v in our_dictionary.items() if v == our_value ]
# look for a known key and return the value
return [ our_dictionary[known_key] if known_key in our_dictionary else "Unknown key" ]

python/tuplelistdict.txt · Last modified: 2013/03/16 17:41 (external edit)