Data Types

The main data types in python are:

  • Numbers;
  • String;
  • List;
  • Set;
  • Dictionary;

Numbers

Operators

In [1]:
2 + 3
Out[1]:
5
In [2]:
2 - 3
Out[2]:
-1
In [3]:
2 * 3
Out[3]:
6
In [4]:
2**3
Out[4]:
8
In [5]:
2 / 3
Out[5]:
0.6666666666666666
In [6]:
5 // 3
Out[6]:
1
In [7]:
5 % 3
Out[7]:
2

A complete list of operators is in the Python Documentation

Number types

In [8]:
2 / 3.  # float
Out[8]:
0.6666666666666666
In [9]:
int(2 / 3.)
Out[9]:
0
In [10]:
int('1')
Out[10]:
1
In [11]:
float(1)
Out[11]:
1.0
In [12]:
float('1.3')
Out[12]:
1.3
In [13]:
long(1.300)
Out[13]:
1
In [14]:
complex(2, 3)
Out[14]:
(2+3j)
In [15]:
complex('2+3j')
Out[15]:
(2+3j)

Assign a variable

In [16]:
one = 1
In [17]:
one
Out[17]:
1

Assign more than one variable at the same time

In [18]:
two, three, four = 2, 3, 4
In [20]:
print(four, three)
4 3
In [21]:
a = b = c = 1
In [22]:
a
Out[22]:
1
In [23]:
b
Out[23]:
1
In [24]:
c
Out[24]:
1
In [25]:
#working only with python3
a, *b, c = [1, 2, 3, 4, 5, 6]
In [26]:
a == 1
Out[26]:
True
In [27]:
b == [2, 3, 4, 5]
Out[27]:
True
In [28]:
c == 6
Out[28]:
True
In [29]:
complex0 = -3j  # complex
In [30]:
complex0.imag
Out[30]:
-3.0
In [31]:
complex0.real
Out[31]:
-0.0
In [32]:
complex0**2
Out[32]:
(-9+0j)

abs, pow, round

In [33]:
abs(-1.45)
Out[33]:
1.45
In [34]:
pow(2, 3)
Out[34]:
8

To get more function we should load the math library

In [1]:
import math
round(math.pi, ndigits=3)
Out[1]:
3.142

Hands on!

In [ ]:
pietro = 0
In [ ]:
round(

Use python as a scientific calculator [1 minute]:

In [2]:
x = 2 # assign a variable
y = 3
x * y
Out[2]:
6
In [ ]:
 
In [37]:
math.sin(math.pi/2.) # use functions and variables from the math library
# if you import the math library with:
# from math import *
# become: sin(pi/2.)
Out[37]:
1.0
In [3]:
a = 10.5
b = 10.5
In [4]:
a == b
Out[4]:
True
In [5]:
a is b
Out[5]:
False

Boolean

In [38]:
true = True
false = False
none = None
one = 1
zero = 0
a = 'a'
In [39]:
true is True # use "is" to check that is the same object
Out[39]:
True
In [40]:
false is not True
Out[40]:
True
In [41]:
true == True
Out[41]:
True
In [145]:
a = 12
b = 12
a is b
Out[145]:
True
In [146]:
a = 12345678901234567890
b = 12345678901234567890
a is b
Out[146]:
False
In [147]:
a = 0.1
b = 0.1
a is b
Out[147]:
False
In [42]:
one > zero # >/>=/</<=
Out[42]:
True
In [43]:
one > zero and zero > -one
Out[43]:
True
In [44]:
one < zero or zero < -one
Out[44]:
False

String

To define a string we must use one of ",':

In [45]:
string ='qwertyuiopasdfghjklzxcvbnm'

In python we can see a string as an array of characters, the first element of a list index == 0

(Python as C and oder languages start from 0).

In [46]:
string[0]  # get the first element of the string
Out[46]:
'q'
In [47]:
len(string)  # get the lenght of the string
Out[47]:
26
In [48]:
string[25]  # get the last element of the string
Out[48]:
'm'
In [49]:
string[-1]  # get the last
Out[49]:
'm'

Slicing in python, we use ":" to divide the start, finish and the step.

In [50]:
string[0:6] # start=0, stop=6
Out[50]:
'qwerty'
In [51]:
string[::3] # step=3
Out[51]:
'qrupdhlcn'

Hands on!

Reverse the string using slice [1 minute]

Solution:

In [52]:
# using: start 0, end the last with a negative step
string[::-1]
Out[52]:
'mnbvcxzlkjhgfdsapoiuytrewq'

String are not a modifiable object

In [53]:
numb = '0123-5678'
In [54]:
numb[4]
Out[54]:
'-'

If we try to modify the fourth character python raise an error, because this operation are not allowed by the string class.

In [55]:
numb[4] = 4
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-55-e9e2a6cd0e69> in <module>()
----> 1 numb[4] = 4

TypeError: 'str' object does not support item assignment

Mathematical operation with the strings, only summation and multiplication are allowed.

In [56]:
'a'+'b'+'c'
Out[56]:
'abc'
In [57]:
'abc'-'c'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-57-7baa0de4424e> in <module>()
----> 1 'abc'-'c'

TypeError: unsupported operand type(s) for -: 'str' and 'str'
In [58]:
'a'*4
Out[58]:
'aaaa'

Hands on!

Substitute the character '-' with '4' using the slice and the mathematical properties of the string class. [2 minutes]

Possible solution:

In [60]:
numb[:4] + '4' + numb[5:]
Out[60]:
'012345678'

Define a multirow string

In python we can simple need to add somewhere the character "\n" inside the string

In [61]:
multirow = 'Things that I like in python:\n    - syntax;\n    - power.\n'
print(multirow)
Things that I like in python:
    - syntax;
    - power.

In [62]:
multirow = """Things that I like in python:
    - syntax;
    - power.
"""
print(multirow)
Things that I like in python:
    - syntax;
    - power.

String as objects: some methods of the string class.

In [63]:
findstr = "find something inside"
In [64]:
findstr.find('s')
Out[64]:
5
In [65]:
findstr[9:]
Out[65]:
'thing inside'
In [66]:
findstr[9:].find('s')
Out[66]:
8
In [67]:
print(multirow.replace('syntax', "it's nice"))
Things that I like in python:
    - it's nice;
    - power.

In [68]:
stripstr = '   some spaces    '
In [69]:
stripstr.strip() # try the effect of: lstrip, rstrip
Out[69]:
'some spaces'
In [6]:
splitstr = "split a long phrase, with a lot of words!"
In [9]:
first, secnd = splitstr.split(',')  # specify with character should be use to split the string, the defaul is ' '
In [10]:
secnd
Out[10]:
' with a lot of words!'

Hands on!

Play with the string using some other methods like: upper, capitalize, lower, isdigit, islower, etc. [2 minutes]

In [72]:
character = 'A strAngE strIng'
character.lower()
Out[72]:
'a strange string'
In [73]:
numbers = '1234'
numbers.isdigit()
Out[73]:
True

String formatting (as in C)

In [74]:
'python is %s!!!' % 'beautiful'
Out[74]:
'python is beautiful!!!'
In [75]:
import math
'number int: %05d, float: %f' % (15, math.pi)
Out[75]:
'number int: 00015, float: 3.141593'
In [76]:
'number int: %d, float: %05.2f' % (15, math.pi*100)
Out[76]:
'number int: 15, float: 314.16'
In [77]:
'list: %r' % [1,2,3,4]
Out[77]:
'list: [1, 2, 3, 4]'
In [78]:
'%3d%%' % 15
Out[78]:
' 15%'

String formatting using the "format" method

In [79]:
'SELECT {cols} FROM {table}'.format(cols='cat, name', table='streets')
Out[79]:
'SELECT cat, name FROM streets'
In [80]:
'SELECT {} FROM {}'.format('cat, name','streets')
Out[80]:
'SELECT cat, name FROM streets'

Hands on!

Using the following variables:

In [11]:
integer = -12345
double = 3.141592653589793
word = 'python'
Get the following strings [3 minutes]: "Still missing: -12345 €" "the pigreco value is around: 3.14159" " python "

A possible solution:

In [82]:
"Still missing: %d €" % integer
"Still missing: {} €".format(integer)
Out[82]:
'Still missing: -12345 €'
In [83]:
"the pigreco value is around: %.5f" % double
"the pigreco value is around: {:.5f}".format(double)
Out[83]:
'the pigreco value is around: 3.14159'
In [84]:
'   %s   ' % word
'   {}   '.format(word)
Out[84]:
'   python   '

List

In [12]:
list_one = ["a", "b", "c", [1,2,3], "d"]
In [14]:
list_one[3][1]
Out[14]:
2
In [87]:
list_one[0]
Out[87]:
'a'

If we use a negative index we start from the last

In [88]:
list_one[-2]
Out[88]:
[1, 2, 3]

Using the ":" we separate the index of the first element, the last, and the step [first:last:step], these operation is called slicing.

In [89]:
list_one[1:4]
Out[89]:
['b', 'c', [1, 2, 3]]
In [90]:
list_one[::2]
Out[90]:
['a', 'c', 'd']
In [91]:
list_one[::-1]
Out[91]:
['d', [1, 2, 3], 'c', 'b', 'a']

List methods

In [92]:
list_one.append('a')
list_one
Out[92]:
['a', 'b', 'c', [1, 2, 3], 'd', 'a']
In [93]:
list_one.count('a')
Out[93]:
2
In [94]:
len(list_one)
Out[94]:
6
In [95]:
list_one.pop(-1)
Out[95]:
'a'
In [98]:
list_one.index('b')
Out[98]:
1
In [99]:
list_one.extend(['e','f','g','h'])
In [100]:
list_one
Out[100]:
['a', 'b', 'c', [1, 2, 3], 'd', 'e', 'f', 'g', 'h']
In [18]:
list_one[3].append(11)
list_one
Out[18]:
['a', 'b', 'c', [0, 1, 10, 2, 3, 11], 'd']
In [103]:
list_one.insert(1, [4,5,6])
list_one
Out[103]:
['a', [4, 5, 6], 'b', 'c', [0, 1, 2, 3], 'd', 'e', 'f', 'g', 'h']
In [104]:
list_one[-3:]=[]
list_one
Out[104]:
['a', [4, 5, 6], 'b', 'c', [0, 1, 2, 3], 'd', 'e']
In [105]:
list_one.remove('e')
list_one
Out[105]:
['a', [4, 5, 6], 'b', 'c', [0, 1, 2, 3], 'd']
In [106]:
'a' in list_one
Out[106]:
True

Tuple

As a list but is unmodifiable

In [107]:
tuple_one = (1,2,3,':-)')
In [108]:
tuple_one.index(2)
Out[108]:
1
In [109]:
tuple_one.count(':-)')
Out[109]:
1
In [110]:
2 in tuple_one
Out[110]:
True
In [111]:
tuple_one[0]
Out[111]:
1
In [112]:
tuple_one[0] = 10
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-112-9bf63db863c3> in <module>()
----> 1 tuple_one[0] = 10

TypeError: 'tuple' object does not support item assignment

Set

Another data types that is available in python is "set".

In [113]:
gis = set(['arcgis', 'mapinfo', 'qgis', 'grass', 'udig'])
opensource = set(['qgis', 'grass', 'udig'])
usingpython = set(['qgis', 'grass', 'arcgis'])
In [114]:
gis - opensource
Out[114]:
{'arcgis', 'mapinfo'}
In [115]:
opensource & usingpython  # and
Out[115]:
{'grass', 'qgis'}
In [116]:
opensource ^ usingpython  # or
Out[116]:
{'arcgis', 'udig'}

Dictionary

The last data type used in python that we see today is the dictionary, lets define a dictionary with the address number.

In [19]:
contact = {'pietro': 333123808, 'jonh': 123123123}
In [118]:
contact['pietro']
Out[118]:
333123808
In [119]:
contact['pietro'] = {'cell': 333123808, 'tel': '04545454'}
In [120]:
contact['pietro']['cell']
Out[120]:
333123808

Hands on!

Add your contact into the the contact dictionary.

Some dictionary methods: keys, values, items [1 minute]

In [121]:
contact.items()
Out[121]:
dict_items([('jonh', 123123123), ('pietro', {'tel': '04545454', 'cell': 333123808})])
In [122]:
contact.keys()
Out[122]:
dict_keys(['jonh', 'pietro'])
In [22]:
contact['pietro:123'] = 0
In [23]:
 
Out[23]:
{'jonh': 123123123, 'pietro': 333123808, 'pietro:123': 0, (1, 2, 3): 1}

Verify the type of an object

To verify the type of an object we have some usefull function like:

  • type
  • isinstance
In [123]:
type(contact)
Out[123]:
builtins.dict
In [124]:
type(1)
Out[124]:
builtins.int
In [125]:
isinstance(contact, dict)
Out[125]:
True

Hands on!

Verify the type of the other objects that we have define untill now. [2 minutes]

In [ ]:
 

Other types from collecions

In [126]:
import collections
In [130]:
ordered = collections.OrderedDict([('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', 4), ('f', 5), ('g', 6)])
list(ordered.keys())
Out[130]:
['a', 'b', 'c', 'd', 'e', 'f', 'g']
In [131]:
unordered = dict([('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', 4), ('f', 5), ('g', 6)])
list(unordered.keys())
Out[131]:
['f', 'g', 'd', 'e', 'b', 'c', 'a']
In [133]:
getpoint = collections.namedtuple('Point', ('x', 'y'))
In [134]:
pnt = getpoint(1, 2)
pnt
Out[134]:
Point(x=1, y=2)
In [135]:
pnt.x
Out[135]:
1
In [136]:
pnt.y
Out[136]:
2
In [137]:
pnt[0]
Out[137]:
1
In [138]:
deque = collections.deque()
deque
Out[138]:
deque([])
In [139]:
deque.append(0)
deque
Out[139]:
deque([0])
In [140]:
deque.append(1)
deque
Out[140]:
deque([0, 1])
In [141]:
deque.appendleft(2)
deque
Out[141]:
deque([2, 0, 1])
In [142]:
deque.popleft()
Out[142]:
2
In [143]:
deque.pop()
Out[143]:
1
In [144]:
deque
Out[144]:
deque([0])