Python vs Java (Modified from http://hyperpolyglot.org/)

a side-by-side reference sheet

Indexes:    arithmetic and logic | strings | regexes | dates and time | arrays and lists | sets | dictionaries | functions | execution control | files | directories | processes and environment | libraries and modules | objects | reflection | web | tests | debugging and profiling | interop

python (1991)

java (1995)

versions used
 

2.7; 3.2

SE6; SE7

implicit prologue

import os, re, sys

none

show version
 

$ python -V

$ javac --version

interpreter/complier
 

$ python foo.py

$ javac foo.java

repl
 

$ python

$ java

command line script

$ python -c "print('hi')"

$

statement separator
 

newline or ;

newlines not separators inside (), [], {}, triple quote literals, or after backslash: \

 ;


block delimiters
 

offside rule

{}

assignment
 

assignments can be chained but otherwise don't return values:
v = 1

int v = 1;

parallel assignment
 

x, y, z = 1, 2, 3
# raises ValueError:
x, y = 1, 2, 3
# raises ValueError:
x, y, z = 1, 2

none

swap
 

x, y = y, x

none

compound assignment operators: arithmetic, string, logical, bit

# do not return values:
+= -= *= /= //= %= **=
+= *=
&= |= ^=
<<= >>= &= |= ^=

+= -= *= /=  %=
+= *=
&&= ||= ^=
<<= >>= &= |= ^=

increment and decrement
 

none

none

local variable declarations
 

# in function body:
v = None
a, d = [], {}
x = 1
y, z = 2, 3

String v = null;

int x = 1;

int y = 2;

regions which define local scope

nestable (read only):
  function or method body

top level:
  file
  class
  method body

nestable:
  anonymous class
  anonymous block

global variable

g1, g2 = 7, 8
def swap_globals():
  global g1, g2
  g1, g2 = g2, g1

int x=1;

constant declaration
 

# uppercase identifiers
# constant by convention

PI = 3.14

# warning if capitalized
# identifier is reassigned

Final Double PI = 3.14;

to-end-of-line comment
 

# comment

# comment

comment out multiple lines
 

use triple quote string literal:
'''comment line
another line'''

//
/*
 */

null
 

None

null

null test
 

v == None
v is None

v == null

undefined variable access
 

raises NameError

?

undefined test
 

not_defined = False
try: v
except NameError: not_defined = True

?

arithmetic and logic

python

java

true and false
 

True False

true false

falsehoods
 

False None 0 0.0 '' [] {}

false null

logical operators
 

and or not

&& || !

conditional expression
 

x if x > 0 else -x

x > 0 ? x : -x

comparison operators
 

comparison operators are chainable:
== != > < >= <=

== != > < >= <=

three value comparison

removed from Python 3:
cmp(0, 1)
cmp('do', 're')

none

convert from string, to string
 

7 + int('12')
73.9 + float('.037')
'value: ' + str(8)

7 + Integer.parseInt("12")
73.9 + Float.parseFloat("0.37")
"value: " + String.valueOf("8")

arithmetic operators
 

+ - * / // % **

+ - * / %

integer division and divmod
 

13 // 5
q, r = divmod(13, 5)

int quotient= 13 / 5;
int remaineder=13%5;

float division
 

float(13) / 5
# Python 3:
13 / 5

13.0 / 5 or
5/1.0

arithmetic functions
 

from math import sqrt, exp, log, \
sin, cos, tan, asin, acos, atan, atan2

import java.lang.Math;

Math.sqrt Math.exp Math.log Math.sin Math.cos Math.tan Math.asin Math.acos Math.atan Math.atan2

arithmetic truncation
 

import math

int(x)
int(round(x))
math.ceil(x)
math.floor(x)
abs(x)

import java.lang.Math;

(long)3.77
Math.round(3.77)
(long)Math.floor(3.77)
(long)Math.ceil(3.77)

min and max
 

min(1,2,3)
max(1,2,3)
min([1,2,3])
max([1,2,3])

none

division by zero
 

raises ZeroDivisionError

throws ArithmeticException

integer overflow
 

becomes arbitrary length integer of type long

?

float overflow
 

raises OverflowError

?

sqrt -2
 

# raises ValueError:
import math
math.sqrt(-2)

# returns complex float:
import cmath
cmath.sqrt(-2)

throws ArithmeticException

rational numbers
 

from fractions import Fraction

x = Fraction(22,7)
x.numerator
x.denominator

complex numbers
 

z = 1 + 1.414j
z.real
z.imag

none

random integer, uniform float, normal float

import random

random.randint(0,99)
random.random()
random.gauss(0,1)

import java.util.Random;

Random rand=new Random();

rand.nextInt(100);

rand.nextDouble();

set random seed, get and restore seed

import random

random.seed(17)
sd = random.getstate()
random.setstate(sd)

import java.util.Random;

Random rand=new Random(10);
Random rand=new Random();

rand.setSeed(20);

bit operators
 

<< >> & | ^ ~

<< >> & | ^ ~

binary, octal, and hex literals and conversions

0b101010   bin()
052        oct()
0x2a     hex()

0b101010
052
0x2a

base conversion

int("60", 7)

Integer. parseInt(42, 8);

strings

python

java

string literal
 

'don\'t say "no"'
"don't say \"no\""
"don't " 'say "no"'
'''don't say "no"'''
"""don't say "no\""""

"don't say \"no\""

newline in literal
 

triple quote literals only

no

character escapes
 

single and double quoted:
\newline \\ \' \" \a \b \f \n \r \t \v \ooo \xhh

Python 3:
\uhhhh \Uhhhhhhhh

double quoted:
\b \f \n \r \t \uhhhh \\ \" \' \o \oo \ooo

variable interpolation
 

count = 3
item = 'ball'
print('{count} {item}s'.format(
  **locals()))

int count = 3;
String item = "ball";
System.out.println(count+” ”+item);

custom delimiters

none

none

sprintf
 

'lorem %s %d %f' % ('ipsum', 13, 3.7)

fmt = 'lorem {0} {1} {2}'
fmt.format('ipsum', 13, 3.7)

none

here document
 

none

none

concatenate
 

s = 'Hello, '
s2 = s + 'World!'

juxtaposition can be used to concatenate literals:
s2 = 'Hello, ' "World!"

s = "Hello, ";
s2 = s + "World!";


replicate
 

hbar = '-' * 80

none

split, in two, with delimiters, into characters

'do re mi fa'.split()
'do re mi fa'.split(None, 1)
re.split('(\s+)', 'do re mi fa')
list('abcd')

"do re mi fa".split(" ");
"abcd".split("");

join
 

' '.join(['do', 're', 'mi', 'fa'])

none

case manipulation

'lorem'.upper()
'LOREM'.lower()
'lorem'.capitalize()

"lorem".toUpperCase();
"LOREM".toLowerCase();

strip
 

' lorem '.strip()
' lorem'.lstrip()
'lorem '.rstrip()

" lorem ".trim()

pad on right, on left
 

'lorem'.ljust(10)
'lorem'.rjust(10)

none

length
 

len('lorem')

"lorem".length()

index of substring
 

'do re re'.index('re')
'do re re'.rindex('re')
raise ValueError if not found

"do re re".indexOf("re")
"do re re".indexOf("re", 5)
return -1 if not found

extract substring
 

'lorem ipsum'[6:11]

"lorem ipsum".substring(10,13)

extract character

'lorem ipsum'[6]

"lorem ipsum".charAt(3)

chr and ord
 

chr(65)
ord('A')

char d=(char)100;
int d=(int)’d’;

character translation
 

from string import lowercase as ins
from string import maketrans

outs = ins[13:] + ins[:13]
'hello'.translate(maketrans(ins,outs))

regexes

python

java

literal, custom delimited literal

re.compile('lorem|ipsum')
none

character class abbreviations and anchors

char class abbrevs:
. \d \D \s \S \w \W

anchors: ^ $ \A \b \B \Z

match test
 

if re.search('1999', s):
  print('party!')

case insensitive match test

re.search('lorem', 'Lorem', re.I)

modifiers
 

re.I re.M re.S re.X

substitution
 

s = 'do re mi mi mi'
s = re.compile('mi').sub('ma', s)

match, prematch, postmatch
 

m = re.search('\d{4}', s)
if m:
  match = m.group()
  prematch = s[0:m.start(0)]
  postmatch = s[m.end(0):len(s)]

boolean isMatch = "hello".matches(".*ll.*");

group capture
 

rx = '(\d{4})-(\d{2})-(\d{2})'
m = re.search(rx, '2010-06-03')
yr, mo, dy = m.groups()

rx = /(\d{4})-(\d{2})-(\d{2})/
m = rx.match("2010-06-03")
yr, mo, dy = m[1..3]

scan
 

s = 'dolor sit amet'
a = re.findall('\w+', s)

a = "dolor sit amet".scan(/\w+/)

backreference in match and substitution

none

rx = re.compile('(\w+) (\w+)')
rx.sub(r'\2 \1', 'do re')

/(\w+) \1/.match("do do")

"do re".sub(/(\w+) (\w+)/, '\2 \1')

recursive regex

none

none

date/time

python

java

date/time type
 

datetime.datetime

java.util.Date

current date/time

import datetime

t = datetime.datetime.now()
utc = datetime.datetime.utcnow()

long millis = System.currentTimeMillis();
Date dt = new Date(millis);

to unix epoch, from unix epoch

from datetime import datetime as dt

epoch = int(t.strftime("%s"))
t2 = dt.fromtimestamp(1304442000)

long epoch = dt.getTimeInMillis()/1000;

Date dt2 = new Date(epoch * 1000);

current unix epoch

import datetime

t = datetime.datetime.now()
epoch = int(t.strftime("%s"))

epoch = Time.now.to_i

strftime

t.strftime('%Y-%m-%d %H:%M:%S')

DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s2 = fmt.format(dt);

get HOUR_OF_DAY, DAY_OF_WEEK, etc

line=106,2007-02-20 00:05:41,121.480600,31.319600, 92, 90,1”

day_of_week = int(time.strftime("%w", time.strptime("{timestamp}".format(**line), "%Y-%m-%d %H:%M:%S")))

            hour_of_day = int(time.strftime("%H", time.strptime("{timestamp}".format(**line), "%Y-%m-%d %H:%M:%S")))

            minute = int(time.strftime("%M", time.strptime("{timestamp}".format(**line), "%Y-%m-%d %H:%M:%S")))

            sec = int(time.strftime("%S", time.strptime("{timestamp}".format(**line), "%Y-%m-%d %H:%M:%S")))

DateFormat fmt = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
Date dt = fmt.format(“
2011-08-23 19:35:59.411135”);

Calendar cl=Calendar.getNewInstance();

cl.setTime(dt);

System.out.println(cl.get(Calendar.HOUR_OF_DAY));

System.out.println(cl.get(Calendar.DAY_OF_WEEK));

System.out.println(cl.get(Calendar.MINUTE));

System.out.println(cl.get(Calendar.SECOND));

System.out.println(cl.get(Calendar.MILLISECOND));

default format example

2011-08-23 19:35:59.411135

2011-08-23 17:44:53 -0700

strptime

from datetime import datetime

s = '2011-05-03 10:00:00'
fmt = '%Y-%m-%d %H:%M:%S'
t = datetime.strptime(s, fmt)

String s = "2011-05-03 17:00:00";
Date dt2 = fmt.parse(s);

parse date w/o format

# pip install python-dateutil
import dateutil.parser

s = 'July 7, 1999'
t = dateutil.parser.parse(s)

result of date subtraction

datetime.timedelta object

Float containing time difference in seconds

add time duration

import datetime

delta = datetime.timedelta(
  minutes=10,
  seconds=3)
t = datetime.datetime.now() + delta

require 'date/delta'

s = "10 min, 3 s"
delta = Date::Delta.parse(s).in_secs
t = Time.now + delta

local timezone

a datetime object has no timezone information unless a tzinfo object is provided when it is created

if no timezone is specified the local timezone is used

timezone name; offset from UTC; is daylight savings?

import time

tm = time.localtime()
  
time.tzname[tm.tm_isdst]
(time.timezone / -3600) + tm.tm_isdst
tm.tm_isdst

t.zone
t.utc_offset / 3600
t.dst?

microseconds

t.microsecond

t.usec

sleep

import time

time.sleep(0.5)

sleep(0.5)

timeout

import signal, time

class Timeout(Exception): pass

def timeout_handler(signo, fm):
  raise Timeout()

signal.signal(signal.SIGALRM,
  timeout_handler)

try:
  signal.alarm(5)
  time.sleep(10)
except Timeout:
  pass
signal.alarm(0)

require 'timeout'

begin
  Timeout.timeout(5) do
    sleep(10)
  end
rescue Timeout::Error
end

arrays and lists

python

java

literal
 

a = [1, 2, 3, 4]

int[] a = {1, 2, 3, 4};

allocate array on heap

arrays must be allocated on heap

int[] a = new int[10];

arraylist must be allocated on heap

List<T> al=new List<T>(10);

ArrayList<T> al=new ArrayList<T>(anotherAL);

quote words
 

none

none

size
 

len(a)

a.length;

al.size();

empty test
 

not a

if(a.length==0)

if(al.size()==0) or if(al.isEmpty())

lookup
 

a[0]

a[0]

al.get(0)

update
 

a[0] = 'lorem'

a[0] = "lorem";

al.set(0,”new string”);

out-of-bounds behavior

a = []
raises IndexError:
a[10]
raises IndexError:
a[10] = 'lorem'

int[] a ={1,2,3};
throws IndexOutOfBoundError
a[10]      al.get(10);
throws IndexOutOfBoundError
a[10] = "lorem" 

index of array element

a = ['x', 'y', 'z', 'w']
i = a.index('y')

none

int idx = al.indexOf(“obj”);

slice by endpoints, by length
 

select 3rd and 4th elements:
a[2:4]

none

slice to end
 

a[1:]

none

manipulate back
 

a = [6,7,8]
a.append(9)
a.pop()

none

al.add(newObj);

al.remove(obj);

al.remove(idx);

manipulate front
 

a = [6,7,8]
a.insert(0,5)
a.pop(0)

none

al.add(idx, obj);

concatenate

a = [1,2,3]
a2 = a + [4,5,6]
a.extend([4,5,6])

none

al.addAll(anotherAL);

al.addAll(idx, anotherAL);

replicate

a = [None] * 10
a = [None for i in range(0, 10)]

none

ArrayList<T> newAL=new ArrayList<T>(al);

address copy, shallow copy, deep copy

import copy

a = [1,2,[3,4]]
a2 = a
a3 = list(a)
a4 = copy.deepcopy(a)

shallow copy

ArrayList<T> newAL=new ArrayList<T>(al);

deep copy

ArrayList<T> newAL=new ArrayList<T>(al);

Collections.copy(newAL, al);

arrays as function arguments

parameter contains address copy

parameter contains shallow copy

iteration
 

for i in [1,2,3]:
  print(i)

none

for(T  ele: al)

    System.out.println(ele.toString());

indexed iteration

a = ['do', 're', 'mi', 'fa']
for i, s in enumerate(a):
  print('%s at index %d' % (s, i))

for(int i=0;i<a.length;i++)

     System.out.println(a[i]);

 

for(int i=0;i<al.size();i++)

    System.out.println(al.get(i));

iterate over range

range replaces xrange in Python 3:
for i in xrange(1, 1000001):
  code

for(int i=0;i<1000;i++){

    code

}

instantiate range as array

a = range(1, 11)
Python 3:
a = list(range(1, 11))

none

reverse

a = [1,2,3]
a[::-1]
a.reverse()

none

Collections.reverse(al);

sort

a = ['b', 'A', 'a', 'B']
sorted(a)
a.sort()
a.sort(key=str.lower)

none

 

Collections.sort(al, comparator);

dedupe

a = [1,2,2,3]
a2 = list(set(a))
a = list(set(a))

ArrayList deduped = new ArrayList(new HashSet(duplication_al));

sets

python

java

membership
 

7 in a

al.containst(obj);

intersection
 

{1,2} & {2,3,4}

Set intersec=new HashSet(set_1);

intersec.retainAll(set_2);

union
 

{1,2} | {2,3,4}

Set union=new HashSet(set_1);

union.addAll(set_2);

relative complement, symmetric difference

{1,2,3} - {2}
{1,2} ^ {2,3,4}

Set diff=new HashSet(set_1);

diff.removeAll(set_2);

pick random element

from random import shuffle, sample

a = {1, 2, 3, 4}
sample(a,1)

//s is a set

int rand_idx=rand.nextInt(s.size());

int i=0;

for(Object o: s){

   if(i==rand_idx){

         return o;

   }

   i+=1;

}

map
 

map(lambda x: x * x, [1,2,3])
# or use list comprehension:
[x*x for x in [1,2,3]]

filter
 

filter(lambda x: x > 1, [1,2,3])
# or use list comprehension:
[x for x in [1,2,3] if x > 1]

reduce
 

# import needed in Python 3 only
from functools import reduce

reduce(lambda x, y: x+y, [1,2,3], 0)

universal and existential tests
 

all(i%2 == 0 for i in [1,2,3,4])
any(i%2 == 0 for i in [1,2,3,4])

shuffle and sample

from random import shuffle, sample

a = [1, 2, 3, 4]
shuffle(a)
sample(a, 2)

zip
 

# array of 3 pairs:
a = zip([1,2,3], ['a', 'b', 'c'])

dictionaries

python

java

literal
 

d = { 't':1, 'f':0 }

none, has to allocate first

java.util.TreeMap<String, Integer> m = new java.util.TreeMap<String, Integer>();

size
 

len(d)

m.size()

lookup
 

d['t']

m.get("hello")

out-of-bounds behavior
 

d = {}
raises KeyError:
d['lorem']
adds key/value pair:
d['lorem'] = 'ipsum'


returns null:
m["lorem"]
adds key/value pair:
d["lorem"] = "ipsum"

is key present
 

'y' in d

m.containsKey(key);

delete entry

d = {1: True, 0: False}
del d[1]

m.remove(key);

from array of pairs, from even length array

a = [[1,'a'], [2,'b'], [3,'c']]
d = dict(a)

a = [1,'a',2,'b',3,'c']
d = dict(zip(a[::2], a[1::2]))

a = [[1,"a"], [2,"b"], [3,"c"]]
d = Hash[a]

a = [1,"a",2,"b",3,"c"]
d = Hash[*a]

merge

d1 = {'a':1, 'b':2}
d2 = {'b':3, 'c':4}
d1.update(d2)

m1.putAll(m2);

invert

to_num = {'t':1, 'f':0}
# dict comprehensions added in 2.7:
to_let = {v:k for k, v
  in to_num.items()}

to_num = {"t"=>1, "f"=>0}
to_let = to_num.invert

iteration
 

for k, v in d.iteritems():
  code

Python 3:
for k, v in d.items():
  code

for ( java.util.Map.Entry<String, Integer> e : m.entrySet() ) {
  use e.getKey() or e.getValue()
}

keys and values as arrays

d.keys()
d.values()

Python 3:
list(d.keys())
list(d.values())

m.keySet();
none

default value, computed value

from collections import defaultdict

counts = defaultdict(lambda: 0)
counts['foo'] += 1

class Factorial(dict):
  def __missing__(self, k):
    if k > 1:
      return k * self[k-1]
    else:
      return 1

factorial = Factorial()

counts = Hash.new(0)
counts['foo'] += 1

factorial = Hash.new do |h,k|
  k > 1 ? k * h[k-1] : 1
end

functions

python

java

function declaration
 

def add(a, b):
  return a+b

public static int add(int a, int b){

   return a+b;

}