Reputation:
def f(a):
for i in a:
print i
>>> f(i for i in [1,2,3])
1
2
3
>>> f([i for i in [1,2,3]])
1
2
3
>>> f((i for i in (1,)))
1
Did I pass a tupple or list in the first example?
What are the differeces between them?
Upvotes: 2
Views: 63
Reputation: 1
You don't really want to check types because you would defeat the purpose of polymorphism. However, if you really want to know the type of the object, you can call the built-in type() function.
#Python 3.x
a=[1,2,3]
b=(1,2,3)
type(a)
<class 'list'>
type(b)
<class 'tuple'>
Upvotes: 0
Reputation: 5193
You pass a generator and a list:
>>> def f(a):
... print type(a)
... for i in a:
... print i
...
>>> f(i for i in [1,2,3])
<type 'generator'>
1
2
3
>>>
>>> f([i for i in [1,2,3]])
<type 'list'>
1
2
3
>>> f((i for i in (1,)))
<type 'generator'>
1
>>>
Both are iterable in a for-loop, however it works differently. Generator executes a statement every iteration and list (or another Iterables) are a piece of data, all of its elements are present without any operation.
More about generators here
Upvotes: 2