Types in Python

This page gives you information on the main types available in Python, what are the differences between list and tuple and what is the significance of indentation in the language.

Introdution

Python is a programming language currently supported by a community, it is open source and managed by nonprofit organization. The main features are:

  • Interpreted Code
  • Multiplatform
  • Simple
  • Object Oriented

In its structure has some Python statements, calls from high level they are:

  • Integers, Floats Numbers and Boolean (Basic)
  • Lists, Tuples, Strings, Dictionaries, Files and Classes and Instances. (Special)

In case of Lists and Tuples, they are very similar and we call sequences in which figures are indexed and store any value. Their only difference is that tuples once created, can not be changed.

Note: If you have any questions during the program which type of variable assumes
you can use the command type(object).

Let's see some examples to understand how they work:

Examples

Decimal Integer

1 vint1 = 9
2 vint2 = 5
3 vint3 = 8
4 vint4 = 9
5 print "---------------------------------------------------"
6 print "The average is calculated:",(vint1+vint2+vint3+vint4)/4
7 print "---------------------------------------------------"
---------------------------------------------------
The average is calculated: 7
---------------------------------------------------
1 width = 20
2 height = 5*9
3 width * height
4 print "---------------------------------------------------"
5 print "width:",width
6 print "height:",height
7 print "width x height:", (width*height)
8 print "---------------------------------------------------"
---------------------------------------------------
width: 20
height: 45
width x height: 900
---------------------------------------------------

Hexadecimal

 1 print "---------------------------------------------------"
 2 vhex = 0x18A92
 3 print "The 18A92 in Hex is:",vhex
 4 dec = 255
 5 print "The 255 in hex is:",hex(dec)
 6 int1 = 10
 7 int2 = 5
 8 hex1 = 0xff
 9 print "Adding 10(int) + 5(int) + ff(hex) is equal:",(int1+int2+hex1)
10 print "---------------------------------------------------"
---------------------------------------------------
The 18A92 in Hex is: 101010
The 255 in hex is: 0xff
Adding 10(int) + 5(int) + ff(hex) is equal: 270
---------------------------------------------------

String

1 vstring = "The Medical Image Processing"
2 vstring2 = "- Unicamp 2011"
3 print "---------------------------------------------------"
4 print "Text:",vstring,vstring2
5 print "Little Text:",(vstring[4:12] + vstring2[2:]  )
6 print "What is the position of word Medical ? The position is :",vstring.find("edical")
7 print "---------------------------------------------------"
---------------------------------------------------
Text: The Medical Image Processing - Unicamp 2011
Little Text: Medical Unicamp 2011
What is the position of word Medical ? The position is : 5
---------------------------------------------------

Attention

the code below would return the error:"object does not support item assignment" if it were run because you can not change an element of the string.

1 #a = "abcdefghi"
2 #print "array orginal:",a
3 #a[1]='B'
4 #print "array changed:",a

Complex numbers

 1 a = 1j * 1J
 2 b = 1j * complex(0,1)
 3 c = (3+1j)*3
 4 d = 1.5+0.5j
 5 print "---------------------------------------------------"
 6 print "a:",a
 7 print "b:",b
 8 print "c:",c
 9 print "d:",d.real
10 print "d real:",d.real
11 print "d imag.:",d.imag
12 print "---------------------------------------------------"
---------------------------------------------------
a: (-1+0j)
b: (-1+0j)
c: (9+3j)
d: 1.5
d real: 1.5
d imag.: 0.5
---------------------------------------------------

Floating

1 vprice = 10.99
2 vqty = 5
3 print "Total Cost:",vprice*vqty
Total Cost: 54.95
 1 print "---------------------------------------------------"
 2 a = 25.00/3.00
 3 print "A = 25.00/3.00",a
 4 a = a+2
 5 print "Adding + 2 in a",a
 6 print "Type of a ?", type(a)
 7 b = 25/3
 8 print "\n\nB = 25/3",b
 9 b = b+2
10 print "Type of b ?", type(b)
11 print "---------------------------------------------------"
---------------------------------------------------
A = 25.00/3.00 8.33333333333
Adding + 2 in a 10.3333333333
Type of a ? <type 'float'>


B = 25/3 8
Type of b ? <type 'int'>
---------------------------------------------------

Boolean

1 vfoundimage = True  #Boolean
2 print "---------------------------------------------------"
3 if vfoundimage == True:
4    print "The research was completed successfully, the true value."
5 else:
6    print "Error in research ! the value is false,retur with the data."
7 print "---------------------------------------------------"
---------------------------------------------------
The research was completed successfully, the true value.
---------------------------------------------------
 1 print "---------------------------------------------------"
 2 a = 4 == 2
 3 print "4 is equal 2",a
 4 a = 2 != 2
 5 print "4 not equal 2",a
 6 a = 2 < 4
 7 print "2 is less that 4",a
 8 a = 2 > 4
 9 print "2 is larger that 4",a
10 print "---------------------------------------------------"
---------------------------------------------------
4 is equal 2 False
4 not equal 2 False
2 is less that 4 True
2 is larger that 4 False
---------------------------------------------------

Lists

List is a sequence of values ​​indexed by an integer,the list can contain any type of value, including values ​​of mixed types: for see all methods of list execute the command dir(name of list)

 1 print "---------------------------------------------------"
 2 a = ['spam', 'eggs', 100, 1234]
 3 print "List array original:",a
 4 print "Numbers of elements of a:",len(a)
 5 print "Last elements of a:",a[-1]
 6 print "Last but one:",a[-2]
 7 a[2] = a[2] + 23
 8 print "Change individual elements of a list:",a
 9 a[0:2] = [1, 12]
10 print "Replace some items", a
11 a[0:2] = []
12 print "Remove some:",a
13 a[1:1] = ['bletch', 'xyz']
14 print "Insert some:",a
15 a[:] = []
16 print "Clear the List:",a
17 print "---------------------------------------------------"
---------------------------------------------------
List array original: ['spam', 'eggs', 100, 1234]
Numbers of elements of a: 4
Last elements of a: 1234
Last but one: 100
Change individual elements of a list: ['spam', 'eggs', 123, 1234]
Replace some items [1, 12, 123, 1234]
Remove some: [123, 1234]
Insert some: [123, 'bletch', 'xyz', 1234]
Clear the List: []
---------------------------------------------------
1 print "---------------------------------------------------"
2 a = [1,2,12,6,3,20,13]
3 print "Original array",a
4 a.sort()
5 print "Array in ascending",a
6 a.reverse()
7 print "Array in decreasing",a
8 print "---------------------------------------------------"
---------------------------------------------------
Original array [1, 2, 12, 6, 3, 20, 13]
Array in ascending [1, 2, 3, 6, 12, 13, 20]
Array in decreasing [20, 13, 12, 6, 3, 2, 1]
---------------------------------------------------
 1 vpainters= ["Cézzanne","Goya","Da Vinci","Van Gogh"]
 2 vimage= ["Jaz Bouffan","La Nevada","La Gioconda","The yellow house"]
 3 vsize= ["2","5","3","1"]
 4 print "---------------------------------------------------"
 5 print "My favorites painters are:"
 6 print "---------------------------------------------------"
 7 
 8 for item in vpainters:   # Show the painters
 9    print item
10 
11 vpainters.append("Candidate Portinari")
12 vimage.append("Environment")
13 vsize.append("1")
14 print "---------------------------------------------------"
15 print "Display the painters,image and image size"
16 print "after adding a new item"
17 print "---------------------------------------------------"
18 for i in range(0,5):
19     print "painters:" + vpainters[i] + " Image:" + vimage[i] + " Size:" + vsize[i]
---------------------------------------------------
My favorites painters are:
---------------------------------------------------
Cézzanne
Goya
Da Vinci
Van Gogh
---------------------------------------------------
Display the painters,image and image size
after adding a new item
---------------------------------------------------
painters:Cézzanne Image:Jaz Bouffan Size:2
painters:Goya Image:La Nevada Size:5
painters:Da Vinci Image:La Gioconda Size:3
painters:Van Gogh Image:The yellow house Size:1
painters:Candidate Portinari Image:Environment Size:1

Dictionaries

A dictionary is a collection of elements where it is possible using an index of any immutable type.

1 vpizza = {"Mozzarella":21,"Pepperoni":18,"Four Chease":17,"Tuna":21.50}
2 print "---------------------------------------------------"
3 print "Display the value of pizza of tuna:"
4 print "---------------------------------------------------"
5 print "The value of pizza of tuna is :" + str(vpizza["Tuna"])  # in this case is a necessary the conversion of value.
---------------------------------------------------
Display the value of pizza of tuna:
---------------------------------------------------
The value of pizza of tuna is :21.5
1 print "---------------------------------------------------"
2 phonenumber = {"Jonh":5511987645,"Paul":55193087676,"Kate":554134567122}
3 print "The phone number the Paul is:",["Paul"]
4 print "The phone number the Jonh is:",["Jonh"]
5 print "The phone number the Kate is:",["Kate"]
6 print "The elements of dictionari:",phonenumber.items()
7 print "Keys of dictionari:",phonenumber.keys()
8 print "---------------------------------------------------"
---------------------------------------------------
The phone number the Paul is: ['Paul']
The phone number the Jonh is: ['Jonh']
The phone number the Kate is: ['Kate']
The elements of dictionari: [('Paul', 55193087676), ('Jonh', 5511987645), ('Kate', 554134567122)]
Keys of dictionari: ['Paul', 'Jonh', 'Kate']
---------------------------------------------------

Tuples

Remember:Tuples are sequences of arbitrary elements as lists, with the exception that they are immutable.

1 vtuples = ("Tuples a","Tuples b","Tuples c")
2 print "---------------------------------------------------"
3 print "Showing                                            "
4 print "---------------------------------------------------"
5 
6 print "Number of initial registration in tuples:" + str(len(vtuples))
7 # vtuplas.append("vtuples d")
8 # AttributeError: 'tuples' object has no attribute 'append'
9 print "Amount of registration after append:" + str(len(vtuples))
---------------------------------------------------
Showing                                            
---------------------------------------------------
Number of initial registration in tuples:3
Amount of registration after append:3

Identation

Identation in other languages ​​are specific symbols that delimit blocks of code, in Python there is a specific delimiter for blocks of code. Masking is done by indentation This ensures that the code is always readable

  • Benefits: Code but clean
  • Disadvantage: Programmer adapt

In Java / J2me:

  • int i =0;
  • if(i =0)
  • {
  • System.out.println("Nothing Stated");
  • System.out.println("Variable is = " + i);
  • }

In Python

1 print "---------------------------------------------------"
2 i = 0        # In python
3 print "The value of variable is : "
4 if i == 0:
5     print "Nothing Stated"
6     print "Variable:" + str(i)
7 print "---------------------------------------------------"
---------------------------------------------------
The value of variable is : 
Nothing Stated
Variable:0
---------------------------------------------------
1 print "---------------------------------------------------"
2 print "The value of a is:"
3 if a == 0:
4    print "zero"
5    a = "zero"
6 else:
7    print "not equal a zero"
8 print "---------------------------------------------------"
---------------------------------------------------
The value of a is:
not equal a zero
---------------------------------------------------

Class

See the example

 1 class A:
 2    a = 1   # public
 3    __b = 2 # private
 4 
 5 class B(A):
 6    __c = 3 # private
 7 
 8 print "---------------------------------------------------"
 9 a = A()
10 print "The object A is a instance of the classe B ?",isinstance(a, B)
11 a = B()
12 print "The object A is a instance of the classe B ?",isinstance(a, B)
13 b = B()
14 print "The object B is a instance of the classe A ?",isinstance(b, B)
15 b = A()
16 print "The object B is a instance of the classe A ?",isinstance(b, B)
17 print "---------------------------------------------------"
---------------------------------------------------
The object A is a instance of the classe B ? False
The object A is a instance of the classe B ? True
The object B is a instance of the classe A ? True
The object B is a instance of the classe A ? False
---------------------------------------------------
 1 class people:
 2    age = "32"            # public
 3    height = "1.85"     # private
 4 
 5 class people_carac(people):
 6    haircolor = "Black" # private
 7 
 8    def __init__(self,name):
 9 
10      print "---------------------------------------------------"
11      print "Name:",name
12      print "Age:",self.age
13      print "Height:",self.height
14      print "Color Hair:",self.haircolor
15      print "---------------------------------------------------"
16 
17 p = people_carac("Jonh")
---------------------------------------------------
Name: Jonh
Age: 32
Height: 1.85
Color Hair: Black
---------------------------------------------------

Numpy

Numpy is the basic package of Python that lets you work with arrays, vectors and arrays of N dimensions. Written with an easy, he is very similar to matlab, but nevertheless effective because of its fast processing. Properties narray: ndarray.ndim, ndarray.shape, ndarray.size, ndarray.dtype, ndarray.itemsize, ndarray.data

Type of numpy.

Data type Description
bool Boolean (True or False) stored as a byte
int Platform integer (normally either int32 or int64)
int8 Byte (-128 to 127)
int16 Integer (-32768 to 32767)
int32 Integer (-2147483648 to 2147483647)
int64 Integer (9223372036854775808 to 9223372036854775807)
uint8 Unsigned integer (0 to 255)
uint16 Unsigned integer (0 to 65535)
uint32 Unsigned integer (0 to 4294967295)
uint64 Unsigned integer (0 to 18446744073709551615)
float Shorthand for float64.
float16 Half precision float: sign bit, 5 bits exponent, 10 bits mantissa
float32 Single precision float: sign bit, 8 bits exponent, 23 bits mantissa
float64 Double precision float: sign bit, 11 bits exponent, 52 bits mantissa
complex Shorthand for complex128.
complex64 Complex number, represented by two 32-bit floats (real and imaginary components)
complex128 Complex number, represented by two 64-bit floats (real and imaginary components)

Here are some examples

 1 import numpy
 2 print "Exempla of creating an array 4 x 3"
 3 matriz_1 = numpy.arange(12).reshape(4,3)
 4 print "---------------------------------------------------"
 5 print "Matriz 1"
 6 print "---------------------------------------------------"
 7 
 8 print matriz_1
 9 print "Dimension of array 1:" + str(matriz_1.shape)          # Show the dimension of array.
10 matriz_2 = array( [(2,3,4),(6,8,10),(12,14,16),(18,20,22)] )
11 print "---------------------------------------------------"
12 print "Matrix 2"
13 print "---------------------------------------------------"
14 print matriz_2
15 
16 matriz_3 = matriz_1 + matriz_2
17 print "---------------------------------------------------"
18 print "Adding the matrix 1 with 2"
19 print "---------------------------------------------------"
20 print  matriz_3
21 
22 
23 matriz_4 = matriz_2 - matriz_1
24 print "---------------------------------------------------"
25 print "Subtracting the matrix 2 of matrix 1"
26 print "---------------------------------------------------"
27 print  matriz_3
28 
29 vn = -2
30 matriz_5 = matriz_1 * vn
31 print "---------------------------------------------------"
32 print "Multiplying any matrix 1 por N = - 2"
33 print "---------------------------------------------------"
34 print  matriz_5
35 
36 
37 matriz_6 = zeros( (4,3), dtype=int16 )
38 print "---------------------------------------------------"
39 print "Creating an array filled with the  0"
40 print "---------------------------------------------------"
41 print  matriz_6
42 
43 matriz_7 = ones( (4,3), dtype=int16 )
44 print "---------------------------------------------------"
45 print "Creating an array filled with the 1"
46 print "---------------------------------------------------"
47 print  matriz_7
Exempla of creating an array 4 x 3
---------------------------------------------------
Matriz 1
---------------------------------------------------
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]
Dimension of array 1:(4, 3)
---------------------------------------------------
Matrix 2
---------------------------------------------------
[[ 2  3  4]
 [ 6  8 10]
 [12 14 16]
 [18 20 22]]
---------------------------------------------------
Adding the matrix 1 with 2
---------------------------------------------------
[[ 2  4  6]
 [ 9 12 15]
 [18 21 24]
 [27 30 33]]
---------------------------------------------------
Subtracting the matrix 2 of matrix 1
---------------------------------------------------
[[ 2  4  6]
 [ 9 12 15]
 [18 21 24]
 [27 30 33]]
---------------------------------------------------
Multiplying any matrix 1 por N = - 2
---------------------------------------------------
[[  0  -2  -4]
 [ -6  -8 -10]
 [-12 -14 -16]
 [-18 -20 -22]]
---------------------------------------------------
Creating an array filled with the  0
---------------------------------------------------
[[0 0 0]
 [0 0 0]
 [0 0 0]
 [0 0 0]]
---------------------------------------------------
Creating an array filled with the 1
---------------------------------------------------
[[1 1 1]
 [1 1 1]
 [1 1 1]
 [1 1 1]]

Example with Indexing and Slicing

 1 import numpy
 2 
 3 a = arange(10)**3
 4 print "---------------------------------------------------"
 5 print "Array a:",a
 6 print "Position a[2]:",a[2]
 7 print "Position 2 util 5 of array a:",a[2:5]
 8 a[:6:2] = -1000
 9 print "New array a:",a
10 print "---------------------------------------------------"
---------------------------------------------------
Array a: [  0   1   8  27  64 125 216 343 512 729]
Position a[2]: 8
Position 2 util 5 of array a: [ 8 27 64]
New array a: [-1000     1 -1000    27 -1000   125   216   343   512   729]
---------------------------------------------------

Example Ndimension

 1 import numpy
 2 
 3 
 4 def f(x,y):
 5      return 10*x+y
 6 
 7 b = fromfunction(f,(5,4),dtype=int)
 8 print "---------------------------------------------------"
 9 print "Array b:",b
10 print "Array b[2,3]:",b[2,3]
11 print "Array b[:,1]:",b[:,1]
12 print "Array b[1:3,:]",b[1:3,:]
13 print "---------------------------------------------------"
---------------------------------------------------
Array b: [[ 0  1  2  3]
 [10 11 12 13]
 [20 21 22 23]
 [30 31 32 33]
 [40 41 42 43]]
Array b[2,3]: 23
Array b[:,1]: [ 1 11 21 31 41]
Array b[1:3,:] [[10 11 12 13]
 [20 21 22 23]]
---------------------------------------------------

Others examples

 1 import numpy
 2 
 3 print "---------------------------------------------------"
 4 a = arange(10).reshape(2,5)
 5 print "Array a:",a
 6 b = zeros( (3,4) )
 7 print "Array b:",b
 8 c = ones( (3,4) )
 9 print "Array c:",c
10 print "---------------------------------------------------"
---------------------------------------------------
Array a: [[0 1 2 3 4]
 [5 6 7 8 9]]
Array b: [[ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]]
Array c: [[ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]]
---------------------------------------------------
 1 import numpy
 2 a = numpy.arange(4).reshape(2,2)
 3 print "---------------------------------------------------"
 4 print type(a)
 5 # using the array called
 6 b = array([ [2,3],[4,5]] )
 7 print type(b)
 8 print "A:\n",a
 9 print "B:\n",b
10 # types array
11 print "Zeros:\n",zeros((3,2))
12 print "Ones:\n",ones((3,2))
13 print "Empty:\n",empty((3,2),int)
14 x = "Linspace:\n",linspace( 0, 1, 5 )
15 print x
16 #operations on array
17 c = a+b        #
18 print "Multiplication by a scalar array",2*c
19 print
20 print "Multiplication of array", a*b
21 print
22 print "Point multiplication of elements",dot(a,b)
23 print
24 print "Checking information in less than 10",dot(a,b)<10
25 print
26 print "Sum of elements in each column",dot(a,b).sum(axis=0)
27 print "observation of the smallest element of each row",dot(a,b).min(axis=1)
28 print "---------------------------------------------------"
---------------------------------------------------
<type 'numpy.ndarray'>
<type 'numpy.ndarray'>
A:
[[0 1]
 [2 3]]
B:
[[2 3]
 [4 5]]
Zeros:
[[ 0.  0.]
 [ 0.  0.]
 [ 0.  0.]]
Ones:
[[ 1.  1.]
 [ 1.  1.]
 [ 1.  1.]]
Empty:
[[                  0 4607182418800017408]
 [4607182418800017408 4607182418800017408]
 [4607182418800017408 4607182418800017408]]
('Linspace:\n', array([ 0.  ,  0.25,  0.5 ,  0.75,  1.  ]))
Multiplication by a scalar array [[ 4  8]
 [12 16]]

Multiplication of array [[ 0  3]
 [ 8 15]]

Point multiplication of elements [[ 4  5]
 [16 21]]

Checking information in less than 10 [[ True  True]
 [False False]]

Sum of elements in each column [20 26]
observation of the smallest element of each row [ 4 16]
---------------------------------------------------