what is difference between [None] and [] in python? [duplicate] - python

This question already has answers here:
What is a None value?
(9 answers)
Is there a difference between "==" and "is"?
(13 answers)
Closed 6 years ago.
I think [None] is same as [], but in my test , maybe there is something...
>>>print len([])
0
>>>print len([None])
1
when should i use the None ? and []
and another interesting question
>>>c= []
>>>d= []
>>>print c is d
False
>>>a= 1
>>>b=1
print a is b
True
why empty list's id granting that is different?

[] is an empty list
[None] is a list with one element. That one element is None
is checks for reference equality. If both objects refer to the same object by reference then is will return true.
a = []
b = a
a is [] #false
a is b #true

[None] does not mean that there is nothing in the list. None is a keyword in python which has a special meaning. It is like NIL or NULL in other languages.
When you say [None], you are saying "I would like to have a list which contains the special object called None". This is different than saying "I would like a list which contains no elements" (by typing []).

Question 1:
None is an object. It is of type "NoneType".
This can be seen by doing something like this in the terminal:
>>> type(None)
<type 'NoneType'>
So, when you put this object in a list, the list has one element.
Question 2:
The assignment operator in Python, =, is used to attach a name to an object. In the case of immutable objects, like integers, multiple names can be attached to the same object. That is what you are doing with a and b. So, when you test their identity, using the is operator, you see that the two names point to the identical object.
Alternatively, when you attach a name to a newly created list (which you created with the [] operator) it is a different list each time.

None is a valid element, but you can treat it like a stub or placeholder. So it counts as an element inside the list even if there is only a None.
For (equality) comparisons you shouldn't use is. Use ==!
Because is can lead to strange behaviour if you don't know exactly when and how to use it. For example:
>>> 1900 is 1900
True
>>> a = 1900
>>> b = 1900
>>> a is b
False
>>> a, b = 1900, 1900
>>> a is b
True
This rather strange behaviour is explained for example in this question: Why does Python handle '1 is 1**2' differently from '1000 is 10**3'?
This won't happen when you use ==:
>>> a == b
True
>>> 1900 == 1900
True
like one would expect.

You want to use None to imply that there is no valid object. You want to use [] to imply an object that is of type list and has no elements.
[None] is a list with one element which is None
>>>c= [] # This is a new list object
>>>d= [] # This is another new list object
In Python , x is y is used to check whether x and y are the same objects.
Here, c and d point to different list objects.
so,
>>>print c is d
False
is expected.
On the other hand,
>>>c= [] # This is a new list object
>>>d = c # This is the same object as c
>>>print c is d
True
Here, a and b are primitives, not objects
>>>a= 1
>>>b=1
So, this is expected:
print a is b
True

Related

Ordered subset in python [duplicate]

This question already has answers here:
How to test if one string is a subsequence of another?
(4 answers)
Python list filtering: remove subsets from list of lists
(10 answers)
Closed 4 years ago.
I know many similar questions has been asked before with answers but my concern is related to builtin functionality rather than my own logic of loops and indexes etc.
In my python app, I need to check if listA is subset of listB. I've done this with the help of sets like this
set(listA) < set(listB)
It works fine overall but I also need to check order of objects in list. e.g.
x = ['a','b','c','d']
xx = ['a', 'c']
xxx = ['c' , 'a']
so according to sets definition;
set(xx) < set(x) returns true and set(xxx) < set(x) also returns true...
But I need something that returns false for 2nd case.
Is there any builtin functionality in python or I need to implement my own logic to get required result?
I think a better word for this operation is a subsequence.
You need to write this yourself, but you can do it fairly easily by walking both lists together:
def is_subsequence(a, b):
b_it = iter(b)
try:
for a_val in a:
while next(b_it) != a_val:
pass
except StopIteration:
return False
else:
return True
used as:
>>> is_subsequence(xx, x)
True
>>> is_subsequence(xxx, x)
False
Edit: Searching for "subsequence" finds this great answer.

False matching with 0 in a list python [duplicate]

This question already has answers here:
Differentiate False and 0
(3 answers)
Closed 5 years ago.
this line evaluates to True in python
False in [0,1,2]
because False and 0 are equal after typecasting.
Is there any way to avoid this typecasting?
Something like === operator for list?
(I know that I can handle this case with a loop by explicitly checking for value types, but I am curious if there is some short and sweet trick to do this without a loop).
First of all, there is no typecasting in Python. False == 0 is true because bool is a subclass of int, and the two objects really are equal.
And no, there is no === operator, you need to explicitly test for types if you don't want this to happen:
lst = [....]
testvalue = False
if any(testvalue == elem and type(testvalue) is type(elem) for elem in lst):
# lst contains testvalue and it is the same type
This explicitly asserts that the two objects are the exact same type, disallowing for subclasses.
Yes, this is a loop. But in for a list also uses a loop, only internally, and both the in containment check and any() short circuit, they return True as soon as the first match is found.
Note that this would disallow float equality too. 0.0 == 0 is true too, but by testing for exact types you disallow that as well. The same goes for complex numbers, and Decimal():
>>> 0j == 0 == 0.0 == Decimal('0')
True
bool is just another numeric type here, albeit one limited to the numeric values 0 and 1.
The better approach, going forward, is to use type hinting in your code; the type hints checker would catch issues like you using booleans where integers or numbers are expected.
If you really feel the need to do the same you can as follows.
False in filter(lambda x: isinstance(x, bool), [0, 1, 2])
Or as #JonClements suggested
any(x is False for x in [0, 1, 3]) # Since immutable values (including
# boolean) are instantiated only once.
However, such use case seldom arises where you need to differentiate between 0 and False as both are falsy as far as Python is concerned. Perhaps, you need to re-think your use-case.
You can use "is" keyword for this.
>>> False == 0
True
>>> False is 0
False

Why are the lines given as tuples in matplotlib [duplicate]

This question already has answers here:
What is the purpose of the single underscore "_" variable in Python?
(5 answers)
Closed 8 months ago.
Reading through Peter Norvig's Solving Every Sudoku Puzzle essay, I've encountered a few Python idioms that I've never seen before.
I'm aware that a function can return a tuple/list of values, in which case you can assign multiple variables to the results, such as
def f():
return 1,2
a, b = f()
But what is the meaning of each of the following?
d2, = values[s] ## values[s] is a string and at this point len(values[s]) is 1
If len(values[s]) == 1, then how is this statement different than d2 = values[s]?
Another question about using an underscore in the assignment here:
_,s = min((len(values[s]), s) for s in squares if len(values[s]) > 1)
Does the underscore have the effect of basically discarding the first value returned in the list?
d2, = values[s] is just like a,b=f(), except for unpacking 1 element tuples.
>>> T=(1,)
>>> a=T
>>> a
(1,)
>>> b,=T
>>> b
1
>>>
a is tuple, b is an integer.
_ is like any other variable name but usually it means "I don't care about this variable".
The second question: it is "value unpacking". When a function returns a tuple, you can unpack its elements.
>>> x=("v1", "v2")
>>> a,b = x
>>> print a,b
v1 v2
The _ in the Python shell also refers to the value of the last operation. Hence
>>> 1
1
>>> _
1
The commas refer to tuple unpacking. What happens is that the return value is a tuple, and so it is unpacked into the variables separated by commas, in the order of the tuple's elements.
You can use the trailing comma in a tuple like this:
>>> (2,)*2
(2, 2)
>>> (2)*2
4

Is it better to use "is" or "==" for number comparison in Python? [duplicate]

This question already has answers here:
Is there a difference between "==" and "is"?
(13 answers)
Closed 1 year ago.
Is it better to use the "is" operator or the "==" operator to compare two numbers in Python?
Examples:
>>> a = 1
>>> a is 1
True
>>> a == 1
True
>>> a is 0
False
>>> a == 0
False
Use ==.
Sometimes, on some python implementations, by coincidence, integers from -5 to 256 will work with is (in CPython implementations for instance). But don't rely on this or use it in real programs.
Others have answered your question, but I'll go into a little bit more detail:
Python's is compares identity - it asks the question "is this one thing actually the same object as this other thing" (similar to == in Java). So, there are some times when using is makes sense - the most common one being checking for None. Eg, foo is None. But, in general, it isn't what you want.
==, on the other hand, asks the question "is this one thing logically equivalent to this other thing". For example:
>>> [1, 2, 3] == [1, 2, 3]
True
>>> [1, 2, 3] is [1, 2, 3]
False
And this is true because classes can define the method they use to test for equality:
>>> class AlwaysEqual(object):
... def __eq__(self, other):
... return True
...
>>> always_equal = AlwaysEqual()
>>> always_equal == 42
True
>>> always_equal == None
True
But they cannot define the method used for testing identity (ie, they can't override is).
>>> a = 255556
>>> a == 255556
True
>>> a is 255556
False
I think that should answer it ;-)
The reason is that some often-used objects, such as the booleans True and False, all 1-letter strings and short numbers are allocated once by the interpreter, and each variable containing that object refers to it. Other numbers and larger strings are allocated on demand. The 255556 for instance is allocated three times, every time a different object is created. And therefore, according to is, they are not the same.
That will only work for small numbers and I'm guessing it's also implementation-dependent. Python uses the same object instance for small numbers (iirc <256), but this changes for bigger numbers.
>>> a = 2104214124
>>> b = 2104214124
>>> a == b
True
>>> a is b
False
So you should always use == to compare numbers.
== is what you want, "is" just happens to work on your examples.
>>> 2 == 2.0
True
>>> 2 is 2.0
False
Use ==

Meaning of using commas and underscores with Python assignment operator? [duplicate]

This question already has answers here:
What is the purpose of the single underscore "_" variable in Python?
(5 answers)
Closed 8 months ago.
Reading through Peter Norvig's Solving Every Sudoku Puzzle essay, I've encountered a few Python idioms that I've never seen before.
I'm aware that a function can return a tuple/list of values, in which case you can assign multiple variables to the results, such as
def f():
return 1,2
a, b = f()
But what is the meaning of each of the following?
d2, = values[s] ## values[s] is a string and at this point len(values[s]) is 1
If len(values[s]) == 1, then how is this statement different than d2 = values[s]?
Another question about using an underscore in the assignment here:
_,s = min((len(values[s]), s) for s in squares if len(values[s]) > 1)
Does the underscore have the effect of basically discarding the first value returned in the list?
d2, = values[s] is just like a,b=f(), except for unpacking 1 element tuples.
>>> T=(1,)
>>> a=T
>>> a
(1,)
>>> b,=T
>>> b
1
>>>
a is tuple, b is an integer.
_ is like any other variable name but usually it means "I don't care about this variable".
The second question: it is "value unpacking". When a function returns a tuple, you can unpack its elements.
>>> x=("v1", "v2")
>>> a,b = x
>>> print a,b
v1 v2
The _ in the Python shell also refers to the value of the last operation. Hence
>>> 1
1
>>> _
1
The commas refer to tuple unpacking. What happens is that the return value is a tuple, and so it is unpacked into the variables separated by commas, in the order of the tuple's elements.
You can use the trailing comma in a tuple like this:
>>> (2,)*2
(2, 2)
>>> (2)*2
4

Categories

Resources