Python "++" operator doesn't work [duplicate] - python

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Python: Behaviour of increment and decrement operators
Hi, I've tried this.
++num
and the num doesn't change at all, always show the value when initialized
if I change ++num to num+=1 then it works.
So, my question is how that ++ operator works?

There isn't a ++ operator in python. You're applying unary + twice to the variable.

Answer: there is no ++ operator in Python. += 1 is the correct way to increment a number, but note that since integers and floats are immutable in Python,
>>> a = 2
>>> b = a
>>> a += 2
>>> b
2
>>> a
4
This behavior is different from that of a mutable object, where b would also be changed after the operation:
>>> a = [1]
>>> b = a
>>> a += [2]
>>> b
[1, 2]
>>> a
[1, 2]

Related

Check if two variables are equal from three choices [duplicate]

This question already has answers here:
Python: determining whether any item in sequence is equal to any other
(5 answers)
Closed 3 years ago.
I have three integers, and I need to check if two of them are equal. The code I have is quite ugly:
a = 5
b = 7
c = 5
if a == b or b == c or a == b:
pass
I wonder if there is a better alternative to this kind of comparation.
You could just build a set and check the resulting length:
a = 5
b = 7
c = 5
if len({a,b,c}) < 3:
pass
Since you mention in your real case the variables are lists, you could convert them to tuples which are hashable and hence can build a set from them. So instead you could do:
a = [5, 2]
b = [7, 2]
c = [5, 2]
if len(set(map(tuple, [a,b,c]))) < 3:
pass
Because you are having lists, you won't be able to use a set directly. If so, you will get an error:
TypeError: unhashable type: 'list'
Convert your lists to tuples, then use the following:
if len(set([tuple(a),tuple(b), tuple(c)])) < 3:
pass

Changing a collection.Counter during enumeration? [duplicate]

This question already has answers here:
How does a for loop evaluate its argument
(3 answers)
Closed 6 years ago.
counter = Counter()
// fill data into counter
for a, b in counter.most_common():
if (b > 1):
counter[a] = np.log(b)
else:
counter[a] = -np.log((1 / (b+0.01)))
As I see, this is safe, based on my trial. No bad thing happens when I change the collection while I am enumerating it. In other languages, in each cycle of the for, the counter.most_common() value is evaluated.
Doesn't this happen in Python as well?
No, it doesn't. A more illustrative example:
def example():
print("Ping")
return [1,2,3,4]
for x in example():
print(x)
Output:
Ping
1
2
3
4

compare two lists in python and print the difference [duplicate]

This question already has answers here:
Compute list difference [duplicate]
(17 answers)
Closed 7 years ago.
I have two lists and I want to print the difference between them (if there is 1 difference, it should print "1". How can I fix that?
So what I have is:
a= ["1","2","3"]
b= ["1","4","5"]
The answer should be 2.
It depends on what do you mean by difference. If they are equal in length and you want to find out the difference, do:
c = [i for i in a if i not in b]
print len(c)
Use set:
print len(set(L1) - set(L2))
Test:
>>> L1 = [1,2,5]
>>> L2 = [8,1]
>>> len(set(L1) - set(L2))
2

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