cdelsola
cdelsola

Reputation: 437

Type Testing Elements of a List

Can somebody please provide some commentary on the following results. I am particularly confused by what I am actually doing when I write: alist = [None]*5 in #1 and why the 'is' statement is False , but isinstance is True in #3 Much appreciated.

#1
>>> alist = [None]*5

>>> alist

[None, None, None, None, None]

>>> type(alist[0])

<type 'NoneType'>

>>> type(alist[0]) is None
False

#2
>>> alist = [int]*5
>>> alist

[<type 'int'>, <type 'int'>, <type 'int'>, <type 'int'>, <type 'int'>]

>>> type(alist[0]) is int

False

>>> isinstance(alist[0],int)

False

#3
>>> alist = [0.0]*5

>>>type(alist[0])

<type 'float'>

>>> alist[0] is float

False

>>> isinstance(alist[0],float)

True

Upvotes: 0

Views: 84

Answers (1)

Sebastian
Sebastian

Reputation: 1889

what I am actually doing when I write: alist = [None]*5 in

You are calling the * operator on a list. See here: http://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange

why the 'is' statement is False

because <type 'NoneType'> is not None, it's the type of None.

isinstance is True in #3

because alist[0] is an instance of the type float. Wasn't that dificult, was it?

Upvotes: 2

Related Questions