Pages

Wednesday, August 14, 2013

Type checking in Python

Python's value has a type, however a variable can be assigned to any typed value.
>>> a = A()
>>> a is A
False
>>> id(a)
3567120
>>> id(A)
2377856

>>> id(type(a))
2377856

>>> type(a) is A
True

>>> a.__class__ is A
True

>>> isinstance(a, A)
True

Equalities

It seems to be simple to compare two values: 1 == 1 or 2 == 3? However, when a variable is assigned to a value, it's a little bit more complicated: x = 3, y = 3, x == y? The different type of data can represent the same value: 1.0 == 0?

Lisp

> (= 1.0 1)
T

> (eql 1.0 1)
NIL

> (eql (cons 'a nil) (cons 'a nil)
NIL

> (setf x (cons 'a nil))
> (eql x x)
T

> (equal x (cons 'a nil))
T

C/C++

int x = 10;
int y = 20;

x == y // equal in Lisp
&x == &y // eql in Lisp
10 == 20 // = in Lisp

Python

>>> x = 10
>>> id(x)
1764365084

>>> y = 10
>>> id(y)
1764365084

>>> x is y // eql in LISP
True

>>> x == y // equal in LISP
True

>>> a = [1,2,3]
>>> a == [1,2,3]
True

>>> a is [1,2,3]
False

>>> id(a)
4359792
>>> id([1,2,3])
4225424

Reference

Merge two lists in Python

When you merge two lists with Python, you can use the overloaded '+' operator.
a = [1,2,3]
b = [2,3,4]

>>> a + b
[1, 2, 3, 2, 3, 4]
However, when you don't want the duplicate values, you need to use set. '+' operator is not supported in a set, so use union() method.
>>> set(a).union(b)
set([1, 2, 3, 4])
You can convert a set to list with list() method.
>>> list(set(a).union(b))
[1, 2, 3, 4]
Refer to set in python document.