Python Basic Doubt
Gary Herron
gary.herron at islandtraining.com
Sat Aug 10 17:48:23 EDT 2013
On 08/10/2013 11:00 AM, Xavi wrote:
> Hello,
>
> El 10/08/2013 18:40, Tim Chase escribió:
>> Generally, if you are using the "is" operator to compare against
>> anything other than None, you're doing it wrong. There are exceptions
>> to this, but it takes knowing the particulars.
>
> Now I have one doubt, I use 'is' to compare basic types in python 3,
> for example .-
>
> v = []
> if type(v) is list:
> print('Is list...')
>
> Because I think it is more clear and faster than .-
> type(v) == [].__class__ ... or ... isinstance(v, list)
>
> Is this correct?
> Thanks.
No! Don't do that! If you want to compare values use the "==" operator.
This is an oversimplification, but generally useful for all beginner
(and most advanced) programmers:
Don't use "is" for comparisons. Use "==".
It 20 years of programming Python, I've *needed* to use "is" ... only
once or twice.
Beyond that, there is a small batch of comparisons where "is" is
slightly more Pythonic, but not really necessary. And beyond that,
there are several instances where the difference between "is" and "==""
are important.
Mostly, using "is" is inappropriate and will get you into compassions
that depend on implementation details. For instance don't use "is"
until you understand this:
q:~> python3
Python 3.3.1 (default, Apr 17 2013, 22:32:14)
[GCC 4.7.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 101 is 1+100
True
>>> 1001 is 1+1000
False
Gary Herron
More information about the Python-list
mailing list