Built-in Data Types

Python has built-in support for a number of data types, like boolean, integer, float and complex numbers, as well as strings.
Here we'll show a few examples of how to use them.

The bool type

Boolean values are used to represent truth values. Booleans can have only two values: True or False.

The bool type is defined as a special case of an int, which in such case can only have two possible values, 1 or 0, i.e., True or False.


In [1]:
type(True)


Out[1]:
bool

In [2]:
type(False)


Out[2]:
bool

Comparing things returns a bool


In [3]:
True == True


Out[3]:
True

In [4]:
True == False


Out[4]:
False

In [5]:
False == False


Out[5]:
True

In [6]:
5 == 5


Out[6]:
True

In [7]:
5 == 7


Out[7]:
False

In [8]:
5 != 7


Out[8]:
True

In [9]:
5 > 3


Out[9]:
True

In [10]:
-1 < 0


Out[10]:
True

In [11]:
1 > 0


Out[11]:
True

In [12]:
3.14 > 2.72


Out[12]:
True

In [13]:
3.14 <= 2.72


Out[13]:
False

In [14]:
'Hello!' != 'Hello!'


Out[14]:
False

In [15]:
'Hi!' != 'Hello!'


Out[15]:
True

In [16]:
[1, 2, 3] == [1, 2, 3]


Out[16]:
True

In [17]:
[1, 2, 3] == [4, 5]


Out[17]:
False

The result of a comparison can be stored in a variable and we can use it to do other things


In [18]:
x = 5 == 7
y = 3 != 0

print(x, y)


False True

In [19]:
z = x or y  # Either x or y is True? Yes!

print(z)


True

In [20]:
z = x and y  # Both x and y are True? No!

print(z)


False

Caution! Please!


In [21]:
myvar = 5   # Points myvar to object 5
myvar == 3  # Check if myvar is equal to 3


Out[21]:
False

In [22]:
x = True     # Here x points to a bool
y = "True"   # Here y points to a str
# z = true   # This is an error!!! Here z is undefined.

Anything can be converted to a boolean


In [23]:
bool(True)  # Duh!


Out[23]:
True

In [24]:
bool(False)  # Duh!


Out[24]:
False

In [25]:
bool(0)


Out[25]:
False

In [26]:
bool(5)


Out[26]:
True

In [27]:
bool(-15)


Out[27]:
True

In [28]:
bool(0.0)


Out[28]:
False

In [29]:
bool(3.14)


Out[29]:
True

In [30]:
bool('')  # Is there anything in this string? No!


Out[30]:
False

In [31]:
bool('Hello')  # Is there anything in this string? Yes!


Out[31]:
True

In [32]:
bool([])  # Is there anything in this list? No!


Out[32]:
False

In [33]:
bool([1, 2, 3])  # Is there anything in this list? Yes!


Out[33]:
True

In [34]:
bool(print)  # Even a function can be converted to a boolean.
             # But why would you do that?
             # Well, Python gives you the power!
             # You just have to learn how to use it! ;-)


Out[34]:
True

Please uncomment the line below to see the full docummentation for the bool type.


In [35]:
# help(bool)

The int type

Interger numbers are implemented by the int type. Unlike other programming languages, in Python integers have virtually infinite precision.


In [36]:
type(42)


Out[36]:
int

In [37]:
b = 42

print(b)


42

What operations are supported by an int?


In [38]:
print(dir(int))


['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']

Those '__xxx__' methods are called Python's magic methods.

They are magic in the sense that Python will call them implicitly when you use the corresponding operator.

Some of those methods are a bit advanced, though, and we'll leave it as an exercise to you to learn how to use them.

Let's begin with the basic arithmetic operations.

Arithmetic operators

operator magic method meaning
+ __add__ addition
- __sub__ subtraction
* __mul__ multiplication
/ __truediv__ division
% __mod__ remainder after division
// __floordiv__ truncated division
** __pow__ to the power of
abs __abs__ absolute value of

In [39]:
print('+\t', 29 + 3)
print('-\t', 29 - 3)
print('*\t', 29 * 3)
print('/\t', 29 / 3)
print('%\t', 29 % 3)
print('//\t', 29 // 3)
print('**\t', 29**3)
print('abs()\t', abs(-1))


+	 32
-	 26
*	 87
/	 9.666666666666666
%	 2
//	 9
**	 24389
abs()	 1

Comparison operators

operator magic method meaning
== __eq__ is equal to
!= __ne__ is not equal to
< __lt__ is less than
> __gt__ is greater than
<= __le__ is less than or equal to
>= __ge__ is greater than or equal to

In [40]:
print('==\t', 1 == 2)
print('!=\t', 1 != 2)
print('<\t', 1 < 2)
print('>\t', 1 > 2)
print('<=\t', 1 <= 2)
print('>=\t', 1 >= 2)


==	 False
!=	 True
<	 True
>	 False
<=	 True
>=	 False

Conversion to/from an int


In [41]:
print(int(42))           # __int__          int to int (Duh!)

print(bool(42))          # __bool__         int to bool
print(int(True))         # __int__          bool to int

print(int(3.14))         # __int__          float to int
print(float(42))         # __float__        int to float

print(str(42))           # __str__          int to str
# print(int("Hi!"))      # ERROR!!!         str to int is not supported!

print(42)                # __str__ is implicitly called by print()


42
True
1
3
42.0
42
42

Calling some attributes and methods


In [42]:
i = 42
print(i.real, i.imag)
print(i.numerator, i.denominator)


42 0
42 1

In [43]:
i = 2**63 - 1   # On 64-bit systems, this is the maximum integer number allowed on most programming languages.
print(i)        # This limitation is imposed by the hardware.


9223372036854775807

In [44]:
i.bit_length()  # Number of bits necessary to represent it in binary.
                # The extra bit is for the sign, so 1+63 == 64-bits.


Out[44]:
63

In [45]:
i = 111**222    # In Python integer numbers are implemented in software.
print(i)        # So, they have virtually infinite precision.


11526601811464905773707865407303811202613562967847466663828954398514096830226261308410979821390982323153280388103704741805872385020551651091143800376734005386587541863059289248002222540859286756270121929932032743605723843908215201353960375654259834419996576900685795327058243449921038597677987877668705013464540539053547349025786725436710034276118654441129899232861120964294799812093001719322299452014343786129135014719947936308711797724809983380782039521

In [46]:
i.bit_length()  # That's why it's possible to have very very very large ints. The only
                # limitation is given by how much RAM memory you have installed on your machine.


Out[46]:
1509

Please uncomment the line below to see the full docummentation for the int type.


In [47]:
# help(int)

The float type

Real numbers are implemented by the float type. Like all programming languages, a float is just an approximation to the true value of a real number. This limitation is imposed by the hardware. In Python there is no single precision float! Here all floats are 64-bit accurate, i.e., double precision.


In [48]:
type(3.14)


Out[48]:
float

In [49]:
b = 3.14

print(b)


3.14

What operations are supported by a float?


In [50]:
print(dir(float))


['__abs__', '__add__', '__bool__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getformat__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__int__', '__le__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__pos__', '__pow__', '__radd__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__round__', '__rpow__', '__rsub__', '__rtruediv__', '__setattr__', '__setformat__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', 'as_integer_ratio', 'conjugate', 'fromhex', 'hex', 'imag', 'is_integer', 'real']

Arithmetic operators

operator magic method meaning
+ __add__ addition
- __sub__ subtraction
* __mul__ multiplication
/ __truediv__ division
% __mod__ remainder after division
// __floordiv__ truncated division
** __pow__ to the power of
abs __abs__ absolute value of

In [51]:
print('+\t', 10.71 + 3)
print('-\t', 10.71 - 3)
print('*\t', 10.71 * 3)
print('/\t', 10.71 / 3)
print('%\t', 10.71 % 3)
print('//\t', 10.71 // 3)
print('**\t', 10.71 ** 3)
print('abs()\t', abs(-1.0))


+	 13.71
-	 7.710000000000001
*	 32.13
/	 3.5700000000000003
%	 1.7100000000000009
//	 3.0
**	 1228.4809110000003
abs()	 1.0

Comparison operators

operator magic method meaning
== __eq__ is equal to
!= __ne__ is not equal to
< __lt__ is less than
> __gt__ is greater than
<= __le__ is less than or equal to
>= __ge__ is greater than or equal to

In [52]:
print('==\t', 3.14 == 5)
print('!=\t', 3.14 != 5)
print('<\t', 3.14 < 5)
print('>\t', 3.14 > 5)
print('<=\t', 3.14 <= 5)
print('>=\t', 3.14 >= 5)


==	 False
!=	 True
<	 True
>	 False
<=	 True
>=	 False

Conversion to/from a float


In [53]:
print(float(3.14))       # __float__        float to float (Duh!)

print(bool(3.14))        # __bool__         float to bool
print(float(True))       # __float__        bool to float

print(int(3.14))         # __int__          float to int
print(float(42))         # __float__        int to float

print(str(3.14))         # __str__          float to str
# print(float("Hi!"))    # ERROR!!!         str to float is not supported!

print(3.14)              # __str__ is implicitly called by print()


3.14
True
1.0
3
42.0
3.14
3.14

Calling some attributes and methods


In [54]:
x, y = 3.14, 5.0

print(x.real, x.imag)

print(x.is_integer())         # Is 3.14 == int(3.14)? No!
print(y.is_integer())         # Is 5.0 == int(5.0)? Yes!

print(x.as_integer_ratio())
print(y.as_integer_ratio())


3.14 0.0
False
True
(7070651414971679, 2251799813685248)
(5, 1)

Please uncomment the line below to see the full docummentation for the float type.


In [55]:
# help(float)

The complex type

TODO

The str type

A string is a sequence of characters. You can define a string in four different ways:

'Hello'

"Hello"

'''Hello'''

"""Hello"""

Any of those forms is valid in Python, but try not mix them.

Of course, all rules have an exception, p.ex.:

bad:
'you don't know'

better:
'you don\'t know'

best:
"you don't know"

In which case is okay to mix them.

Anyway, whatever format you choose to use just be consistent in you code!


In [56]:
type('Hello')


Out[56]:
str

In [57]:
s = 'Hello'

print(s)


Hello

What operations are supported by a str?


In [58]:
print(dir(str))


['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

Comparison operators

operator magic method meaning
== __eq__ is equal to
!= __ne__ is not equal to
< __lt__ is less than
> __gt__ is greater than
<= __le__ is less than or equal to
>= __ge__ is greater than or equal to

In [59]:
print('==\t', 'Hi' == 'Hello')
print('!=\t', 'Hi' != 'Hello')
print('<\t', 'Hi' < 'Hello')      # Humm... what's happening here?
print('>\t', 'Hi' > 'Hello')      # Humm... what's happening here?
print('<=\t', 'Hi' <= 'Hello')    # Humm... what's happening here?
print('>=\t', 'Hi' >= 'Hello')    # Humm... what's happening here?


==	 False
!=	 True
<	 False
>	 True
<=	 False
>=	 True

In [60]:
# String comparison uses lexicographical ordering: first the first two items
# are compared, and if they differ this determines the outcome of the comparison.
# If they are equal, the next two items are compared, and so on, until either
# sequence is exhausted.

print(ord('H'), ord('i'))
print(ord('H'), ord('e'), ord('l'), ord('l'), ord('o'))


72 105
72 101 108 108 111

In [61]:
help(ord)


Help on built-in function ord in module builtins:

ord(c, /)
    Return the Unicode code point for a one-character string.


In [62]:
ord('H') < ord('H') or ord('i') < ord('e')  # A-Ha!!! Now we know what happened there!


Out[62]:
False

In [63]:
ord('H') > ord('H') or ord('i') > ord('e')


Out[63]:
True

In [64]:
ord('H') <= ord('H') and ord('i') <= ord('e')


Out[64]:
False

In [65]:
ord('H') >= ord('H') and ord('i') >= ord('e')


Out[65]:
True

Remember! String comparison uses lexicographical ordering. Lexicographical ordering for strings uses the Unicode code point number to order individual characters. However...

...most of times what you may want to compare is the length of strings!


In [66]:
print(len('Hi'), len('Hello'), len('abracadabra'))


2 5 11

In [67]:
print('==\t', len('Hi') == len('Hello'))
print('!=\t', len('Hi') != len('Hello'))
print('<\t', len('Hi') < len('Hello'))
print('>\t', len('Hi') > len('Hello'))
print('<=\t', len('Hi') <= len('Hello'))
print('>=\t', len('Hi') >= len('Hello'))


==	 False
!=	 True
<	 True
>	 False
<=	 True
>=	 False

In [68]:
help(len)


Help on built-in function len in module builtins:

len(obj, /)
    Return the number of items in a container.

Concatenating strings


In [69]:
x = 'Py'
y = 'thon'
z = 'is'
w = 'ok!'

print(x + y + z + w)


Pythonisok!

In [70]:
print(x + y + ' ' + z + ' ' + w)


Python is ok!

In [71]:
x = 'Py'
y = 'thon '   # Note the white space
z = 'is '     # Note the white space
w = 'nice!'

print(x + y + z + w)


Python is nice!

In [72]:
x = 'Py'
y = 'thon'
z = 'is'
w = 'awesome!'

print(' '.join([x + y, z, w]))


Python is awesome!

In [73]:
print(' -*- '.join([x + y, z, w]))


Python -*- is -*- awesome!

Check if a string contains a sub-string


In [74]:
s = 'Python -*- is -*- awesome!'

In [75]:
'-*-' in s


Out[75]:
True

In [76]:
'Python' in s


Out[76]:
True

In [77]:
'Hello' in s


Out[77]:
False

In [78]:
s in s   # Duh!


Out[78]:
True

Build a string of N identical sub-strings


In [79]:
'Ha ' * 5


Out[79]:
'Ha Ha Ha Ha Ha '

In [80]:
'Ha ' * 5 + 'Ha!!!'


Out[80]:
'Ha Ha Ha Ha Ha Ha!!!'

Methods lower, upper and capitalize


In [81]:
s = 'aWeSoMe!'

print(s.lower(), s.upper(), s.capitalize())


awesome! AWESOME! Awesome!

Split a string into sub-strings


In [82]:
s = 'Python -*- is -*- awesome -*- and -*- I -*- love -*- it!'

print(s)


Python -*- is -*- awesome -*- and -*- I -*- love -*- it!

In [83]:
print(s.split(' '))


['Python', '-*-', 'is', '-*-', 'awesome', '-*-', 'and', '-*-', 'I', '-*-', 'love', '-*-', 'it!']

In [84]:
print(s.split('-*-'))


['Python ', ' is ', ' awesome ', ' and ', ' I ', ' love ', ' it!']

In [85]:
s.split('-*-', 1)  # split by at most 1 time.


Out[85]:
['Python ', ' is -*- awesome -*- and -*- I -*- love -*- it!']

In [86]:
s.split('-*-', 3)  # split by at most 3 times.


Out[86]:
['Python ', ' is ', ' awesome ', ' and -*- I -*- love -*- it!']

In [87]:
help(str.split)


Help on method_descriptor:

split(...)
    S.split(sep=None, maxsplit=-1) -> list of strings
    
    Return a list of the words in S, using sep as the
    delimiter string.  If maxsplit is given, at most maxsplit
    splits are done. If sep is not specified or is None, any
    whitespace string is a separator and empty strings are
    removed from the result.

Check if a string starts or ends with a sub-string


In [88]:
print(s)


Python -*- is -*- awesome -*- and -*- I -*- love -*- it!

In [89]:
s.startswith('Py')


Out[89]:
True

In [90]:
s.startswith('Python')


Out[90]:
True

In [91]:
s.startswith('awesome')


Out[91]:
False

In [92]:
s.endswith('!')


Out[92]:
True

In [93]:
s.endswith('it!')


Out[93]:
True

In [94]:
s.endswith('and')


Out[94]:
False

Strings are immutable


In [95]:
S = 'Pithon'
#    -^----
#    012345

# S[1] = 'y'     # This is an ERROR! You can not change the content of a string!

Using the replace method


In [96]:
# It will return a copy of S with all occurrences
# of substring old replaced by new.

ss = S.replace('i', 'y')

print(S)
print(ss)


Pithon
Python

In [97]:
S = 'Hi! How are you?'

ss = S.replace('Hi!', 'Hello!')

print(S)
print(ss)


Hi! How are you?
Hello! How are you?

replace all occurrences


In [98]:
S = 'tattarrattat' + ' # ' + 'abracadabra'

ss = S.replace('a', '-')

print(S)
print(ss)


tattarrattat # abracadabra
t-tt-rr-tt-t # -br-c-d-br-

replace the first 4 occurrences


In [99]:
S = 'tattarrattat' + ' # ' + 'abracadabra'

ss = S.replace('a', '-', 4)

print(S)
print(ss)


tattarrattat # abracadabra
t-tt-rr-tt-t # abracadabra

replace the last 5 occurrences


In [100]:
S = 'tattarrattat' + ' # ' + 'abracadabra'

ss = S

ss = ''.join(reversed(ss))
ss = ss.replace('a', '-', 5)
ss = ''.join(reversed(ss))

print(S)
print(ss)


tattarrattat # abracadabra
tattarrattat # -br-c-d-br-

Please uncomment the line below to see the full docummentation for the str type.


In [101]:
# help(str)