Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the reason for having '//' in Python? [duplicate]

I saw this in someone's code:

y = img_index // num_images 

where img_index is a running index and num_images is 3.

When I mess around with // in IPython, it seems to act just like a division sign (i.e. one forward slash). I was just wondering if there is any reason for having double forward slashes?

like image 700
Pete Avatar asked Oct 08 '09 04:10

Pete


People also ask

What does duplicated do in Python?

The duplicated() method returns a Series with True and False values that describe which rows in the DataFrame are duplicated and not. Use the subset parameter to specify if any columns should not be considered when looking for duplicates.

What causes duplicate records?

“Human error is the most common cause of duplicate medical records,” LeBlanc notes.

Which allows duplicates in Python?

Tuple is a collection which is ordered and unchangeable. Allows duplicate members.

Why duplicate data is a problem?

Lack of Personalization Duplicated records will reduce the confidence that you have in your data, making it difficult to implement personalization in your business. Personalization requires clean and accurate data. Implementing personalization with inaccurate data is worse than having it at all.


2 Answers

In Python 3, they made the / operator do a floating-point division, and added the // operator to do integer division (i.e., quotient without remainder); whereas in Python 2, the / operator was simply integer division, unless one of the operands was already a floating point number.

In Python 2.X:

>>> 10/3 3 >>> # To get a floating point number from integer division: >>> 10.0/3 3.3333333333333335 >>> float(10)/3 3.3333333333333335 

In Python 3:

>>> 10/3 3.3333333333333335 >>> 10//3 3 

For further reference, see PEP238.

like image 151
Mark Rushakoff Avatar answered Sep 22 '22 11:09

Mark Rushakoff


// is unconditionally "flooring division", e.g:

>>> 4.0//1.5 2.0 

As you see, even though both operands are floats, // still floors -- so you always know securely what it's going to do.

Single / may or may not floor depending on Python release, future imports, and even flags on which Python's run, e.g.:

$ python2.6 -Qold -c 'print 2/3' 0 $ python2.6 -Qnew -c 'print 2/3' 0.666666666667 

As you see, single / may floor, or it may return a float, based on completely non-local issues, up to and including the value of the -Q flag...;-).

So, if and when you know you want flooring, always use //, which guarantees it. If and when you know you don't want flooring, slap a float() around other operand and use /. Any other combination, and you're at the mercy of version, imports, and flags!-)

like image 40
Alex Martelli Avatar answered Sep 19 '22 11:09

Alex Martelli