42. Native Types in Python

  • Numbers
  • Strings
  • Lists
  • Tuples
  • Sets
  • Dictionaries
  • Built-in Constants

43. Numbers

Do I really need to tell you about numbers?

44. Integers

Plain integers and long integers are unified in Python. You don’t need to worry about overflow as it will convert to a long automatically.

import sys
a = sys.maxint
print a
b = a*2
print b

45. Integers (cont.)

Integer literals are interpreted as plain integers unless they don’t fit in which case they are automatically converted to longs. You can force a literal to be a long by using ‘l’ or ‘L’ as a suffix.

a = 100000000000000000000000000000000000
print a
b = 10
print b
b = 10L
print b

46. Floats

Floats are implemented as a double in the underlying C. You can see the underlying precision using sys.float_info

import sys
print sys.float_info

47. Some Notes on Division

Integer division returns the floor. If you want to avoid that you can explicitly convert to a float. Converting after the division is too late.

a = 7
b = 2
print a / b
print float(a) / b
print float(a / b)

48. Python 3 Note

Integer division no longer returns the floor. You can recreate this behavior in Python 2.6 by importing from the __future__ module.

from __future__ import division

a = 7
b = 2
print a / b

49. Complex Numbers

Real and imaginary parts are both stored as floats. Imaginary literals can be created using a ‘j’ or ‘J’ suffix or with the complex() function.

a = 1 + 1j
print a.conjugate()
print complex(2, 5)
print a**2
print a.real
print a.imag

50. Complex Math

The math module only supports types which can be converted to floats. For math functions which work with complex numbers use the cmath module.

import cmath
a = 1 + 1j
print cmath.log(a)
print cmath.sqrt(a)

51. Strings

Strings are a sequence type to hold character data. String literals can be enclosed in ‘ or ” characters. The backslash character is an escape character.

a = 'blip' # The string blip
b = "blip" # The string blah

52. Raw Strings

Strings can also be marked as raw strings with a r/R in which case the escape character is not needed.

a = '\n' # newline character
print a
b = r'\n' # the string \n
print b

53. Triple Quoted Strings

We’ve seens triple quoted strings used as comments. They define string literals which can span more than one line and include the newline characters.

a = """
This string is on multiple lines.
It can be very long if you wish.
"""

54. Strings are Immutable

Unlike C, Strings are immutable meaning you cannot change them once they are created.

a = 'My test string'
print a[0]
a[0] = 'b' # This will generate an error.

55. Basic String Formatting

Python uses the same string formatting as printf in C.

  • ‘d’ Signed integer decimal.
  • ‘i’ Signed integer decimal.
  • ‘o’ Signed octal value.
  • ‘x’ Signed hexadecimal (lowercase).
  • ‘X’ Signed hexadecimal (uppercase).
  • ‘e’ Floating point exponential format (lowercase).
  • ‘E’ Floating point exponential format (uppercase).
  • ‘f’ Floating point decimal format.
  • ‘F’ Floating point decimal format.
  • ‘r’ String (converts any Python object using repr()).
  • ‘s’ String (converts any Python object using str()).

56. String Formatting Examples

a = 10
b = 37.0
print '%i %i' % (a, b)
print '%f %f' % (a, b)
print '%s %s' % (a, b)

57. Formatting with Mappings

You can also used named mappings while formatting strings.

print '%(last)s, %(first)s' % {'first': 'Mark', 'last': 'Lavin'}

More on mappings coming up.

58. String Formatting in Python 3

Python 2.6 includes a back-port of new style string formatting as defined by PEP 3101.

# positional arguments
'{0} {1}'.format('Hello', 'World')
# named arguments
'{first} {second}'.format(second='World', first='Hello')

59. String Concatenating

Stings can be combined with the + operator or by using string formatting. Note that the + operator will not change type.

a = 'test'
b = 'string'
c = 10
print a + b
print '%s %s' % (a, b)
print a + c # This will produce an error
print '%s %s' % (a, c)

60. String Methods

There are a number of handy string methods built in. Remeber because strings are immutable they return a new string rather than modifying the calling string.

a = 'my test string'
print a.upper()
print a

61. String Methods Listing

'test'.capitalize() # returns 'Test'
'test'.endswith('a') # returns False
'test'.find('e') # returns 1 (would return -1 if not found)
'test'.lower() # returns 'test'
'test'.replace('t', 'b') # returns 'besb'
'a b c'.split() # returns ['a', 'b', 'c']
'test'.startswith('i') # returns False
'test string'.title() # returns 'Test String'
'test'.upper() # returns 'TEST'

Check out the full list here: http://docs.python.org/library/stdtypes.html#string-methods

62. Lists

List define a zero-indexed squence of objects.

a = [1, 2, 3]

Items in a list do not need to be the same type. Lists can also be nested.

a = [1, 'a', [2, 'b']]

63. Accessing List Items

Accessing items in a list is done with a bracket syntax. You can access one or more index at a time. You can also use negative indexes.

a = [1, 2, 3]
print a[0]
print a[0:1]
print a[-1]

64. Lists Functions

[1, 2, 3].append(4) # Inserts value at the end of the list
[1, 2, 3].extend([4, 5]) # Appends iterable to the end of the list
[1, 2, 3].pop() # Returns first item and removes from the list
[1, 2, 3].count(1) # Returns the number of values which match
[1, 2, 3].index(2) # Returns the first index where value is found
[1, 2, 3].insert(1, 4) # Inserts 4 to position 1
[1, 2, 3].reverse() # Reverses the order of items

Check out the full list here: http://docs.python.org/library/stdtypes.html#mutable-sequence-types

65. List as a Stack

It’s easy to use Python lists as a stack (last-in, first-out).

a = [1, 2, 3]
a.append(4)
print a
print a.pop()
print a
print a.pop()
print a

66. Tuples

Tuples are similar to lists but with one large difference. Tuples are immutable meaning you cannot change their values once they are set. Tuples use a parentheses rather than a bracket.

a = (1, 2, 3)

67. Beware of the Trailing Comma

Parentheses around a tuple are optional. This allows for handy things like swapping values and unpacking tuples or lists. But if you type

a = 1, # a is a tuple (1,)

68. Unpacking Lists and Tuples

It’s possible to unpack a list or tuple:

a, b, c = [1, 2, 3]
print a
print b
print c

69. Simple Variable Swap

Using a similar syntax you can easily swap to variables:

a = 1
b = 2
a, b = b, a
print a
print b

70. Dictionaries

Dictionaries are key-value mappings. In other contexts or languages they are called associative arrays or maps. They are defined by

a = {'key': 'value'}
a['key']
a['new-key'] = 'new-value'

71. Using Dictionaries

You check if a key is in a dictionary using in or use get to return a default value if the key does not exist. Trying to access a key which does not exist raise a KeyError

if 'key' in a:
    print a['key']

print a.get('key') # returns None if not found
print a.get('key', 1) # returns 1 if not found

72. Using Dictionaries (cont.)

You can access all of the keys in a dictionary with the keys function. You can access a list of all values using the values function. You can also iterate over all the key, value pairs using iteritems.

a = {'1': 'a', '2': 'b'}
print a.keys()
print a.values()
for k,v in a.iteritems():
    print 'Key %s' % k
    print 'Value %s' % v

73. Sets

Sets in Python are much like sets in mathematics. They are an un-ordered collection of objects without duplicates. This allows for fast membership detection as well as familiar set operations.

a = set([1, 2, 3])
b = set([2, 4, 6])
a | b # union
a & b # intersection
a - b # difference
a ^ b # symmetric difference

74. Set Comparsions

Comparison operators can be used to check for subsets.

a = set([1, 2, 3])
b = set([1 ,2, 3, 6])
a <= b # Is subset?
a < b # Is strict (non-equal) subset
a >= b # Is superset?
a > b # Is strict (non-equal) superset

75. Sets in Python 3.X

While in Python 2.X you must use the set() function to create sets, Python 3 allows for set literals using a brace syntax.

a = {1, 2, 3}

Note that {} is still an dictionary.

76. Unpacking Positional Arguments

Lists and tuples can be unpacked to fill in positional arguments for a function call using *.

def add(x, y):
    return x + y

data = (1, 2)
print add(*data)

77. Unpacking Keyword Arguments

Dictionaries can be used to fill arguments using **.

def subtract(x, y):
    return x - y

data = {'y': 1, 'x': 3}
print subtract(**data) # same as subtract(y=1, x=3)

78. Built-in Constants

Python has built in logical constants.

True, False, None

79. Notes on Truth

The built-in bool function is used to convert other types to either True or False. For the most part everything in Python is True except for various empty values.

# False values
0, 0.0 # Zero
'', "" # Empty strings
[], () # Empty lists and tuples
{}, None # Empty dictionaries and None

80. Up Next

Creating your own classes!