Python Datatypes


  • Python has local and global variables.
  • Python does not allow to reference a variable that has never been assigned a value.
  • + is the string concatenation operator.
  • Variables are automatically destroyed when they go out of scope

Example: Assigning multiple values at once.
v is a tuple of three elements, and (x, y, z) is a tuple of three variables. Assigning one to the other assigns each of the values of v to each of the variables, in order.

>>> v = ('a', 'b', 'e')
>>> (x, y, z) = v     
>>> x
>>> y
>>> z

Example: Assigning Consecutive Values

>>> range(7)                                                                    
[0, 1, 2, 3, 4, 5, 6]
>>> MONDAY                                                                      


  • String formatting in Python uses the same syntax as the sprintf function in C.

Example: Unlike Java, the '+' does not automatically convert numbers or other types to string form. The str() function converts values to a string form so they can be combined with other strings.

pi = 3.14
##text = 'The value of pi is ' + pi      ## NO, does not work
text = 'The value of pi is '  + str(pi)  ## yes

Example:The first %s is replaced by the value of k; the second %s is replaced by the value of v. All other characters in the string (in this case, the equal sign) stay as they are.

>>> k = "uid"
>>> v = "sa"
>>> "%s=%s" % (k, v) 

Example: String Formatting vs. Concatenating

>>> uid = "sa"
>>> pwd = "secret"
>>> # + is the string concatenation operator
>>> print pwd + " is not a good password for " + uid      
secret is not a good password for sa
>>> print "%s is not a good password for %s" % (pwd, uid) 
secret is not a good password for sa
>>> userCount = 6
>>> print "Users connected: %d" % (userCount, )           
Users connected: 6
>>> # Trying to concatenate a string with a non-string raises an exception
>>> print "Users connected: " + userCount                 
Traceback (innermost last):
  File "<interactive input>", line 1, in ?
TypeError: cannot concatenate 'str' and 'int' objects


  • Defines 1-1 relationships between keys and values.
  • You cannot have duplicate keys in a dictionary
  • You can add new key-value pairs at any time
  • Dictionaries have no order between elements
  • Dictionary keys are case-sensitive
  • Dictionary values can be any datatype.


#Each element is a key-value pair, and the whole set of elements is enclosed in curly braces. 
>>> d = {"server":"mpilgrim", "database":"master"} 
>>> d
{'server': 'mpilgrim', 'database': 'master'}
#'server' is a key, and its associated value, referenced by d["server"], is 'mpilgrim'. 
>>> d["server"]                                    
>>> d["database"]                                  
#You can get values by key, but you can't get keys by value. So d["server"] is 'mpilgrim', but d["mpilgrim"] #raises an exception, because 'mpilgrim' is not a key. 
>>> d["mpilgrim"]

Example: Modifying Dictionaries

>>> d
{'server': 'mpilgrim', 'database': 'master'}
#You can not have duplicate keys in a dictionary. Assigning a value to an existing key will wipe out the old value.
>>> d["database"] = "pubs" 
>>> d
{'server': 'mpilgrim', 'database': 'pubs'}
#You can add new key-value pairs at any time. 
>>> d["uid"] = "sa"        
>>> d
{'server': 'mpilgrim', 'uid': 'sa', 'database': 'pubs'}
#Use del() to remove a key:value pair from a dictionary.
>>> del(d["server"])
#Use len() to get the length of a dictionary
>>> del(d)


  • A list can hold arbitrary objects and can expand dynamically as new items are added.
  • To define a list you use brackets.

li = ["a", "b", "chrys", "z"]

  • A list is an ordered set of elements enclosed in square brackets
  • You can get a subset of a list, called a slice, by specifying two indices.

List Methods

Example: The following example assigns a list with four elements to the variable foo. The elements are:The number 42, the string "hurz", an anonymous function that computes squares and another list with two elements.

>>> foo = [42, 'hurz', lambda x: x**2, [47, '11']]
>>> print foo
[42, 'hurz', <function <lambda> at 0x8119e8c>, [47, '11']]
>>> print foo[3]
[47, '11']
>>> print foo[2](3)
>>> foo[3][0] = 99
>>> print foo
[42, 'hurz', <function <lambda> at 0x8119e8c>, [99, '11']]
>>> for i in foo:
...     print i, "--", type(i)
42 -- <type 'int'>
hurz -- <type 'string'>
<function <lambda> at 0x8119e8c> -- <type 'function'>
[99, '11'] -- <type 'list'>

Example: List methods

  • count() : returns number of occurrences
  • insert(): insert a new item in the list. The numeric argument is the index of the first element that gets bumped out of position.
  • append(): adds a single element to the end of the list.
  • index(): returns the first occurrence of an item.
  • remove(): removes an item.
  • reverse(): reverses a list.
  • sort(): sorts a list.
>>> a = [66.25, 333, 333, 1, 1234.5]
>>> print a.count(333), a.count(66.25), a.count('x')
2 1 0
>>> a.insert(2, -1)
>>> a.append(333)
>>> a
[66.25, 333, -1, 333, 1, 1234.5, 333]
>>> a.index(333)
>>> a.remove(333)
>>> a
[66.25, -1, 333, 1, 1234.5, 333]
>>> a.reverse()
>>> a
[333, 1234.5, 1, 333, -1, 66.25]
>>> a.sort()
>>> a
[-1, 1, 66.25, 333, 333, 1234.5]
>>> a.concatenate('7,77')
>>> a
[-1, 1, 66.25, 333, 333, 1234.5,7,77]

Example: The Difference between extend and append. extend() takes a single argument, which is always a list, and adds each of the elements of that list to the original list. append() takes one argument, which can be any data type, and simply adds it to the end of the list.

>>> li = ['a', 'b', 'c']
>>> li.extend(['d', 'e', 'f']) 
>>> li
['a', 'b', 'c', 'd', 'e', 'f']
>>> len(li)                    
>>> li[-1]
>>> li = ['a', 'b', 'c']
>>> li.append(['d', 'e', 'f']) 
>>> li
['a', 'b', 'c', ['d', 'e', 'f']]
>>> len(li)                    
>>> li[-1]
['d', 'e', 'f']

Example: Slicing a list. You can get a subset of a list, called a “slice”, by specifying two indices. li[:n] will always return the first n elements, and li[n:] will return the rest, regardless of the length of the list.

>>> li
['a', 'b', 'mpilgrim', 'z', 'example']
>>> li[1:3]  
['b', 'mpilgrim']
>>> li[1:-1] 
['b', 'mpilgrim', 'z']
>>> li[0:3]  
['a', 'b', 'mpilgrim']
>>> li
['a', 'b', 'mpilgrim', 'z', 'example']
# li[:3] is the same as li[0:3]
>>> li[:3] 
['a', 'b', 'mpilgrim']
# li[3:] is the same as li[3:5]
>>> li[3:] 
['z', 'example']
#li[:] is shorthand for making a complete copy of a list.
>>> li[:]  
['a', 'b', 'mpilgrim', 'z', 'example']

Example: Searching a List

>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
>>> li.index("example") 
>>> li.index("new")     
>>> li.index("c")       
Traceback (innermost last):
  File "<interactive input>", line 1, in ?
ValueError: list.index(x): x not in list
>>> "c" in li           

Example:Using List Operators. Lists can also be concatenated with the + operator. The * operator works on lists as a repeater.

>>> li = ['a', 'b', 'mpilgrim']
>>> li = li + ['example', 'new'] 
>>> li
['a', 'b', 'mpilgrim', 'example', 'new']
>>> li += ['two']                
>>> li
['a', 'b', 'mpilgrim', 'example', 'new', 'two']
>>> li = [1, 2] * 3              
>>> li
[1, 2, 1, 2, 1, 2]

Example: Parallel sorting of lists. zip() returns a list of tuples, so you have to convert the result of the last zip() back to lists. That's what the map() command does.

data = zip(list1, list2)
list1, list2 = map(list, zip(*data))

List Comprehensions

  • List comprehension provides a compact way of mapping a list into another list by applying a function to each of the elements of the list.
  • List comprehensions do not change the original list.

Example: li is the list you're mapping. Python loops through li one element at a time, temporarily assigning the value of each element to the variable elem. Python then applies the function elem*2 and appends that result to the returned list

>>> li = [1, 9, 8, 4]
>>> [elem*2 for elem in li]      
[2, 18, 16, 8]
>>> # Note that list comprehensions do not change the original list.
>>> li                          
[1, 9, 8, 4]
>>> # It is safe to assign the result of a list comprehension to the variable that you're mapping.
>>> li = [elem*2 for elem in li] 
>>> li
[2, 18, 16, 8]


S = {x² : x in {0 ... 9}}
V = (1, 2, 4, 8, ..., 2¹²)
M = {x | x in S and x even}

In Python, you can write these expression almost exactly like a mathematician would do.

>>> S = [x**2 for x in range(10)]
>>> V = [2**i for i in range(13)]
>>> M = [x for x in S if x % 2 == 0]

Example: Calculation of prime numbers. We first build a list of non-prime numbers, using a single list comprehension, then use another list comprehension to get the "inverse" of the list, which are prime numbers.

>>> noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]
>>> primes = [x for x in range(2, 50) if x not in noprimes]
>>> print primes

Joining Lists and Splitting Strings

  • You have a list of key-value pairs in the form key=value, and you want to join them into a single string. To join any list of strings into a single string, use the join method of a string object.


>>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}
>>> ["%s=%s" % (k, v) for k, v in params.items()]
['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
>>> ";".join(["%s=%s" % (k, v) for k, v in params.items()])

Example: split reverses join by splitting a string into a multi-element list. Note that the delimiter (“;”) is stripped out completely; it does not appear in any of the elements of the returned list.

>>> li = ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
>>> s = ";".join(li)
>>> s
>>> s.split(";")    
['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
>>> s.split(";", 1) 
['server=mpilgrim', 'uid=sa;database=master;pwd=secret']


  • A tuple is an immutable list.
  • Tuples have no methods. You can only use in to see if an element exists in the tuple.
  • Tuples are constructed by the comma operator (not within square brackets), with or without enclosing parentheses, but an empty tuple must have the enclosing parentheses, such as a, b, c or (). A single item tuple must have a trailing comma, such as (d,)
  • The elements have a defined order.
  • Tuples have no methods.
  • Tuples are good for:
    • Faster than lists.
    • Makes code safer.
    • Tuples can be used as keys in a dictionary since they are immutable.
    • Tuples are used in string formatting.

Example: Defining a tuple

>>> t = ("a", "b", "mpilgrim", "z", "example") 
>>> t
('a', 'b', 'mpilgrim', 'z', 'example')
>>> t[0]                                       
>>> t[-1]                                      
>>> t[1:3]                                     
('b', 'mpilgrim')


*A set is an unordered collection with no duplicate elements.

  • Set objects support mathematical operations like union, intersection, difference, and symmetric difference.
  • Example
>>> from sets import Set as set
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> fruit = set(basket)               # create a set without duplicates
>>> fruit
set(['orange', 'pear', 'apple', 'banana'])
>>> 'orange' in fruit                 # fast membership testing
>>> 'crabgrass' in fruit
>>> # Demonstrate set operations on unique letters from two words
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a                                  # unique letters in a
set(['a', 'r', 'b', 'c', 'd'])
>>> a - b                              # letters in a but not in b
set(['r', 'd', 'b'])
>>> a | b                              # letters in either a or b
set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
>>> a & b                              # letters in both a and b
set(['a', 'c'])
>>> a ^ b                              # letters in a or b but not both
set(['r', 'd', 'b', 'm', 'z', 'l'])

irv': 4127, 'jack': 4098}


['guido', 'irv', 'jack']

'guido' in tel


Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.