Julia difference from Python Flashcards
Noteworthy differences from Python
How does Julia’sfor
,if
,while
, etc blocks differ from Python’s?
Noteworthy differences from Python
- Julia’s
for
,if
,while
, etc. blocks are terminated by theend
keyword. Indentation level is not significant as it is in Python. Unlike Python, Julia has nopass
keyword. - Strings are denoted by double quotation marks (
"text"
) in Julia (with three double quotation marks for multi-line strings), whereas in Python they can be denoted either by single ('text'
) or double quotation marks ("text"
). Single quotation marks are used for characters in Julia ('c'
). - String concatenation is done with
*
in Julia, not+
like in Python. Analogously, string repetition is done with^
, not*
. Implicit string concatenation of string literals like in Python (e.g.'ab' 'cd' == 'abcd'
) is not done in Julia. - Python Lists—flexible but slow—correspond to the Julia
Vector{Any}
type or more generallyVector{T}
whereT
is some non-concrete element type. “Fast” arrays like NumPy arrays that store elements in-place (i.e.,dtype
isnp.float64
,[('f1', np.uint64), ('f2', np.int32)]
, etc.) can be represented byArray{T}
whereT
is a concrete, immutable element type. This includes built-in types likeFloat64
,Int32
,Int64
but also more complex types likeTuple{UInt64,Float64}
and many user-defined types as well. - In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.
- Julia’s slice indexing includes the last element, unlike in Python.
a[2:3]
in Julia isa[1:3]
in Python. - Unlike Python, Julia allowsAbstractArrays with arbitrary indexes. Python’s special interpretation of negative indexing,
a[-1]
anda[-2]
, should be writtena[end]
anda[end-1]
in Julia. - Julia requires
end
for indexing until the last element.x[1:]
in Python is equivalent tox[2:end]
in Julia. - In Julia,
:
before any object creates aSymbol
or_quotes_an expression; so,x[:5]
is same asx[5]
. If you want to get the firstn
elements of an array, then use range indexing. - Julia’s range indexing has the format of
x[start:step:stop]
, whereas Python’s format isx[start:(stop+1):step]
. Hence,x[0:10:2]
in Python is equivalent tox[1:2:10]
in Julia. Similarly,x[::-1]
in Python, which refers to the reversed array, is equivalent tox[end:-1:1]
in Julia. - In Julia, ranges can be constructed independently as
start:step:stop
, the same syntax it uses in array-indexing. Therange
function is also supported. - In Julia, indexing a matrix with arrays like
X[[1,2], [1,3]]
refers to a sub-matrix that contains the intersections of the first and second rows with the first and third columns. In Python,X[[1,2], [1,3]]
refers to a vector that contains the values of cell[1,1]
and[2,3]
in the matrix.X[[1,2], [1,3]]
in Julia is equivalent withX[np.ix_([0,1],[0,2])]
in Python.X[[0,1], [0,2]]
in Python is equivalent withX[[CartesianIndex(1,1), CartesianIndex(2,3)]]
in Julia. - Julia has no line continuation syntax: if, at the end of a line, the input so far is a complete expression, it is considered done; otherwise the input continues. One way to force an expression to continue is to wrap it in parentheses.
- Julia arrays are column-major (Fortran-ordered) whereas NumPy arrays are row-major (C-ordered) by default. To get optimal performance when looping over arrays, the order of the loops should be reversed in Julia relative to NumPy (seerelevant section of Performance Tips).
- Julia’s updating operators (e.g.
+=
,-=
, …) are_not in-place_whereas NumPy’s are. This meansA = [1, 1]; B = A; B += [3, 3]
doesn’t change values inA
, it rather rebinds the nameB
to the result of the right-hand sideB = B + 3
, which is a new array. For in-place operation, useB .+= 3
(see alsodot operators), explicit loops, orInplaceOps.jl
. - Julia evaluates default values of function arguments every time the method is invoked, unlike in Python where the default values are evaluated only once when the function is defined. For example, the function
f(x=rand()) = x
returns a new random number every time it is invoked without argument. On the other hand, the functiong(x=[1,2]) = push!(x,3)
returns[1,2,3]
every time it is called asg()
. - In Julia, keyword arguments must be passed using keywords, unlike Python in which it is usually possible to pass them positionally. Attempting to pass a keyword argument positionally alters the method signature leading to a
MethodError
or calling of the wrong method. - In Julia
%
is the remainder operator, whereas in Python it is the modulus. - In Julia, the commonly used
Int
type corresponds to the machine integer type (Int32
orInt64
), unlike in Python, whereint
is an arbitrary length integer. This means in Julia theInt
type will overflow, such that2^64 == 0
. If you need larger values use another appropriate type, such asInt128
,BigInt
or a floating point type likeFloat64
. - The imaginary unit
sqrt(-1)
is represented in Julia asim
, notj
as in Python. - In Julia, the exponentiation operator is
^
, not**
as in Python. - Julia uses
nothing
of typeNothing
to represent a null value, whereas Python usesNone
of typeNoneType
. - In Julia, the standard operators over a matrix type are matrix operations, whereas, in Python, the standard operators are element-wise operations. When both
A
andB
are matrices,A * B
in Julia performs matrix multiplication, not element-wise multiplication as in Python.A * B
in Julia is equivalent withA @ B
in Python, whereasA * B
in Python is equivalent withA .* B
in Julia. - The adjoint operator
'
in Julia returns an adjoint of a vector (a lazy representation of row vector), whereas the transpose operator.T
over a vector in Python returns the original vector (non-op). - In Julia, a function may contain multiple concrete implementations (called_methods_), which are selected via multiple dispatch based on the types of all arguments to the call, as compared to functions in Python, which have a single implementation and no polymorphism (as opposed to Python method calls which use a different syntax and allows dispatch on the receiver of the method).
- There are no classes in Julia. Instead there are structures (mutable or immutable), containing data but no methods.
- Calling a method of a class instance in Python (
x = MyClass(*args); x.f(y)
) corresponds to a function call in Julia, e.g.x = MyType(args...); f(x, y)
. In general, multiple dispatch is more flexible and powerful than the Python class system. - Julia structures may have exactly one abstract supertype, whereas Python classes can inherit from one or more (abstract or concrete) superclasses.
- The logical Julia program structure (Packages and Modules) is independent of the file structure (
include
for additional files), whereas the Python code structure is defined by directories (Packages) and files (Modules). - The ternary operator
x > 0 ? 1 : -1
in Julia corresponds to a conditional expression in Python1 if x > 0 else -1
. - In Julia the
@
symbol refers to a macro, whereas in Python it refers to a decorator. - Exception handling in Julia is done using
try
—catch
—finally
, instead oftry
—except
—finally
. In contrast to Python, it is not recommended to use exception handling as part of the normal workflow in Julia (compared with Python, Julia is faster at ordinary control flow but slower at exception-catching). - In Julia loops are fast, there is no need to write “vectorized” code for performance reasons.
- Be careful with non-constant global variables in Julia, especially in tight loops. Since you can write close-to-metal code in Julia (unlike Python), the effect of globals can be drastic (seePerformance Tips).
- In Julia, rounding and truncation are explicit. Python’s
int(3.7)
should befloor(Int, 3.7)
orInt(floor(3.7))
and is distinguished fromround(Int, 3.7)
.floor(x)
andround(x)
on their own return an integer value of the same type asx
rather than always returningInt
. - In Julia, parsing is explicit. Python’s
float("3.7")
would beparse(Float64, "3.7")
in Julia. - In Python, the majority of values can be used in logical contexts (e.g.
if "a":
means the following block is executed, andif "":
means it is not). In Julia, you need explicit conversion toBool
(e.g.if "a"
throws an exception). If you want to test for a non-empty string in Julia, you would explicitly writeif !isempty("")
. Perhaps surprisingly, in Pythonif "False"
andbool("False")
both evaluate toTrue
(because"False"
is a non-empty string); in Julia,parse(Bool, "false")
returnsfalse
. - In Julia, a new local scope is introduced by most code blocks, including loops and
try
—catch
—finally
. Note that comprehensions (list, generator, etc.) introduce a new local scope both in Python and Julia, whereasif
blocks do not introduce a new local scope in both languages.
Noteworthy differences from Python
How do Julia’s strings differ from Python’s?
Noteworthy differences from Python
- Julia’s
for
,if
,while
, etc. blocks are terminated by theend
keyword. Indentation level is not significant as it is in Python. Unlike Python, Julia has nopass
keyword. - Strings are denoted by double quotation marks (
"text"
) in Julia (with three double quotation marks for multi-line strings), whereas in Python they can be denoted either by single ('text'
) or double quotation marks ("text"
). Single quotation marks are used for characters in Julia ('c'
). - String concatenation is done with
*
in Julia, not+
like in Python. Analogously, string repetition is done with^
, not*
. Implicit string concatenation of string literals like in Python (e.g.'ab' 'cd' == 'abcd'
) is not done in Julia. - Python Lists—flexible but slow—correspond to the Julia
Vector{Any}
type or more generallyVector{T}
whereT
is some non-concrete element type. “Fast” arrays like NumPy arrays that store elements in-place (i.e.,dtype
isnp.float64
,[('f1', np.uint64), ('f2', np.int32)]
, etc.) can be represented byArray{T}
whereT
is a concrete, immutable element type. This includes built-in types likeFloat64
,Int32
,Int64
but also more complex types likeTuple{UInt64,Float64}
and many user-defined types as well. - In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.
- Julia’s slice indexing includes the last element, unlike in Python.
a[2:3]
in Julia isa[1:3]
in Python. - Unlike Python, Julia allowsAbstractArrays with arbitrary indexes. Python’s special interpretation of negative indexing,
a[-1]
anda[-2]
, should be writtena[end]
anda[end-1]
in Julia. - Julia requires
end
for indexing until the last element.x[1:]
in Python is equivalent tox[2:end]
in Julia. - In Julia,
:
before any object creates aSymbol
or_quotes_an expression; so,x[:5]
is same asx[5]
. If you want to get the firstn
elements of an array, then use range indexing. - Julia’s range indexing has the format of
x[start:step:stop]
, whereas Python’s format isx[start:(stop+1):step]
. Hence,x[0:10:2]
in Python is equivalent tox[1:2:10]
in Julia. Similarly,x[::-1]
in Python, which refers to the reversed array, is equivalent tox[end:-1:1]
in Julia. - In Julia, ranges can be constructed independently as
start:step:stop
, the same syntax it uses in array-indexing. Therange
function is also supported. - In Julia, indexing a matrix with arrays like
X[[1,2], [1,3]]
refers to a sub-matrix that contains the intersections of the first and second rows with the first and third columns. In Python,X[[1,2], [1,3]]
refers to a vector that contains the values of cell[1,1]
and[2,3]
in the matrix.X[[1,2], [1,3]]
in Julia is equivalent withX[np.ix_([0,1],[0,2])]
in Python.X[[0,1], [0,2]]
in Python is equivalent withX[[CartesianIndex(1,1), CartesianIndex(2,3)]]
in Julia. - Julia has no line continuation syntax: if, at the end of a line, the input so far is a complete expression, it is considered done; otherwise the input continues. One way to force an expression to continue is to wrap it in parentheses.
- Julia arrays are column-major (Fortran-ordered) whereas NumPy arrays are row-major (C-ordered) by default. To get optimal performance when looping over arrays, the order of the loops should be reversed in Julia relative to NumPy (seerelevant section of Performance Tips).
- Julia’s updating operators (e.g.
+=
,-=
, …) are_not in-place_whereas NumPy’s are. This meansA = [1, 1]; B = A; B += [3, 3]
doesn’t change values inA
, it rather rebinds the nameB
to the result of the right-hand sideB = B + 3
, which is a new array. For in-place operation, useB .+= 3
(see alsodot operators), explicit loops, orInplaceOps.jl
. - Julia evaluates default values of function arguments every time the method is invoked, unlike in Python where the default values are evaluated only once when the function is defined. For example, the function
f(x=rand()) = x
returns a new random number every time it is invoked without argument. On the other hand, the functiong(x=[1,2]) = push!(x,3)
returns[1,2,3]
every time it is called asg()
. - In Julia, keyword arguments must be passed using keywords, unlike Python in which it is usually possible to pass them positionally. Attempting to pass a keyword argument positionally alters the method signature leading to a
MethodError
or calling of the wrong method. - In Julia
%
is the remainder operator, whereas in Python it is the modulus. - In Julia, the commonly used
Int
type corresponds to the machine integer type (Int32
orInt64
), unlike in Python, whereint
is an arbitrary length integer. This means in Julia theInt
type will overflow, such that2^64 == 0
. If you need larger values use another appropriate type, such asInt128
,BigInt
or a floating point type likeFloat64
. - The imaginary unit
sqrt(-1)
is represented in Julia asim
, notj
as in Python. - In Julia, the exponentiation operator is
^
, not**
as in Python. - Julia uses
nothing
of typeNothing
to represent a null value, whereas Python usesNone
of typeNoneType
. - In Julia, the standard operators over a matrix type are matrix operations, whereas, in Python, the standard operators are element-wise operations. When both
A
andB
are matrices,A * B
in Julia performs matrix multiplication, not element-wise multiplication as in Python.A * B
in Julia is equivalent withA @ B
in Python, whereasA * B
in Python is equivalent withA .* B
in Julia. - The adjoint operator
'
in Julia returns an adjoint of a vector (a lazy representation of row vector), whereas the transpose operator.T
over a vector in Python returns the original vector (non-op). - In Julia, a function may contain multiple concrete implementations (called_methods_), which are selected via multiple dispatch based on the types of all arguments to the call, as compared to functions in Python, which have a single implementation and no polymorphism (as opposed to Python method calls which use a different syntax and allows dispatch on the receiver of the method).
- There are no classes in Julia. Instead there are structures (mutable or immutable), containing data but no methods.
- Calling a method of a class instance in Python (
x = MyClass(*args); x.f(y)
) corresponds to a function call in Julia, e.g.x = MyType(args...); f(x, y)
. In general, multiple dispatch is more flexible and powerful than the Python class system. - Julia structures may have exactly one abstract supertype, whereas Python classes can inherit from one or more (abstract or concrete) superclasses.
- The logical Julia program structure (Packages and Modules) is independent of the file structure (
include
for additional files), whereas the Python code structure is defined by directories (Packages) and files (Modules). - The ternary operator
x > 0 ? 1 : -1
in Julia corresponds to a conditional expression in Python1 if x > 0 else -1
. - In Julia the
@
symbol refers to a macro, whereas in Python it refers to a decorator. - Exception handling in Julia is done using
try
—catch
—finally
, instead oftry
—except
—finally
. In contrast to Python, it is not recommended to use exception handling as part of the normal workflow in Julia (compared with Python, Julia is faster at ordinary control flow but slower at exception-catching). - In Julia loops are fast, there is no need to write “vectorized” code for performance reasons.
- Be careful with non-constant global variables in Julia, especially in tight loops. Since you can write close-to-metal code in Julia (unlike Python), the effect of globals can be drastic (seePerformance Tips).
- In Julia, rounding and truncation are explicit. Python’s
int(3.7)
should befloor(Int, 3.7)
orInt(floor(3.7))
and is distinguished fromround(Int, 3.7)
.floor(x)
andround(x)
on their own return an integer value of the same type asx
rather than always returningInt
. - In Julia, parsing is explicit. Python’s
float("3.7")
would beparse(Float64, "3.7")
in Julia. - In Python, the majority of values can be used in logical contexts (e.g.
if "a":
means the following block is executed, andif "":
means it is not). In Julia, you need explicit conversion toBool
(e.g.if "a"
throws an exception). If you want to test for a non-empty string in Julia, you would explicitly writeif !isempty("")
. Perhaps surprisingly, in Pythonif "False"
andbool("False")
both evaluate toTrue
(because"False"
is a non-empty string); in Julia,parse(Bool, "false")
returnsfalse
. - In Julia, a new local scope is introduced by most code blocks, including loops and
try
—catch
—finally
. Note that comprehensions (list, generator, etc.) introduce a new local scope both in Python and Julia, whereasif
blocks do not introduce a new local scope in both languages.
Noteworthy differences from Python
How does Julia’s use of single quotes ‘ differ from Python?
Noteworthy differences from Python
- Julia’s
for
,if
,while
, etc. blocks are terminated by theend
keyword. Indentation level is not significant as it is in Python. Unlike Python, Julia has nopass
keyword. - Strings are denoted by double quotation marks (
"text"
) in Julia (with three double quotation marks for multi-line strings), whereas in Python they can be denoted either by single ('text'
) or double quotation marks ("text"
). Single quotation marks are used for characters in Julia ('c'
). - String concatenation is done with
*
in Julia, not+
like in Python. Analogously, string repetition is done with^
, not*
. Implicit string concatenation of string literals like in Python (e.g.'ab' 'cd' == 'abcd'
) is not done in Julia. - Python Lists—flexible but slow—correspond to the Julia
Vector{Any}
type or more generallyVector{T}
whereT
is some non-concrete element type. “Fast” arrays like NumPy arrays that store elements in-place (i.e.,dtype
isnp.float64
,[('f1', np.uint64), ('f2', np.int32)]
, etc.) can be represented byArray{T}
whereT
is a concrete, immutable element type. This includes built-in types likeFloat64
,Int32
,Int64
but also more complex types likeTuple{UInt64,Float64}
and many user-defined types as well. - In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.
- Julia’s slice indexing includes the last element, unlike in Python.
a[2:3]
in Julia isa[1:3]
in Python. - Unlike Python, Julia allowsAbstractArrays with arbitrary indexes. Python’s special interpretation of negative indexing,
a[-1]
anda[-2]
, should be writtena[end]
anda[end-1]
in Julia. - Julia requires
end
for indexing until the last element.x[1:]
in Python is equivalent tox[2:end]
in Julia. - In Julia,
:
before any object creates aSymbol
or_quotes_an expression; so,x[:5]
is same asx[5]
. If you want to get the firstn
elements of an array, then use range indexing. - Julia’s range indexing has the format of
x[start:step:stop]
, whereas Python’s format isx[start:(stop+1):step]
. Hence,x[0:10:2]
in Python is equivalent tox[1:2:10]
in Julia. Similarly,x[::-1]
in Python, which refers to the reversed array, is equivalent tox[end:-1:1]
in Julia. - In Julia, ranges can be constructed independently as
start:step:stop
, the same syntax it uses in array-indexing. Therange
function is also supported. - In Julia, indexing a matrix with arrays like
X[[1,2], [1,3]]
refers to a sub-matrix that contains the intersections of the first and second rows with the first and third columns. In Python,X[[1,2], [1,3]]
refers to a vector that contains the values of cell[1,1]
and[2,3]
in the matrix.X[[1,2], [1,3]]
in Julia is equivalent withX[np.ix_([0,1],[0,2])]
in Python.X[[0,1], [0,2]]
in Python is equivalent withX[[CartesianIndex(1,1), CartesianIndex(2,3)]]
in Julia. - Julia has no line continuation syntax: if, at the end of a line, the input so far is a complete expression, it is considered done; otherwise the input continues. One way to force an expression to continue is to wrap it in parentheses.
- Julia arrays are column-major (Fortran-ordered) whereas NumPy arrays are row-major (C-ordered) by default. To get optimal performance when looping over arrays, the order of the loops should be reversed in Julia relative to NumPy (seerelevant section of Performance Tips).
- Julia’s updating operators (e.g.
+=
,-=
, …) are_not in-place_whereas NumPy’s are. This meansA = [1, 1]; B = A; B += [3, 3]
doesn’t change values inA
, it rather rebinds the nameB
to the result of the right-hand sideB = B + 3
, which is a new array. For in-place operation, useB .+= 3
(see alsodot operators), explicit loops, orInplaceOps.jl
. - Julia evaluates default values of function arguments every time the method is invoked, unlike in Python where the default values are evaluated only once when the function is defined. For example, the function
f(x=rand()) = x
returns a new random number every time it is invoked without argument. On the other hand, the functiong(x=[1,2]) = push!(x,3)
returns[1,2,3]
every time it is called asg()
. - In Julia, keyword arguments must be passed using keywords, unlike Python in which it is usually possible to pass them positionally. Attempting to pass a keyword argument positionally alters the method signature leading to a
MethodError
or calling of the wrong method. - In Julia
%
is the remainder operator, whereas in Python it is the modulus. - In Julia, the commonly used
Int
type corresponds to the machine integer type (Int32
orInt64
), unlike in Python, whereint
is an arbitrary length integer. This means in Julia theInt
type will overflow, such that2^64 == 0
. If you need larger values use another appropriate type, such asInt128
,BigInt
or a floating point type likeFloat64
. - The imaginary unit
sqrt(-1)
is represented in Julia asim
, notj
as in Python. - In Julia, the exponentiation operator is
^
, not**
as in Python. - Julia uses
nothing
of typeNothing
to represent a null value, whereas Python usesNone
of typeNoneType
. - In Julia, the standard operators over a matrix type are matrix operations, whereas, in Python, the standard operators are element-wise operations. When both
A
andB
are matrices,A * B
in Julia performs matrix multiplication, not element-wise multiplication as in Python.A * B
in Julia is equivalent withA @ B
in Python, whereasA * B
in Python is equivalent withA .* B
in Julia. - The adjoint operator
'
in Julia returns an adjoint of a vector (a lazy representation of row vector), whereas the transpose operator.T
over a vector in Python returns the original vector (non-op). - In Julia, a function may contain multiple concrete implementations (called_methods_), which are selected via multiple dispatch based on the types of all arguments to the call, as compared to functions in Python, which have a single implementation and no polymorphism (as opposed to Python method calls which use a different syntax and allows dispatch on the receiver of the method).
- There are no classes in Julia. Instead there are structures (mutable or immutable), containing data but no methods.
- Calling a method of a class instance in Python (
x = MyClass(*args); x.f(y)
) corresponds to a function call in Julia, e.g.x = MyType(args...); f(x, y)
. In general, multiple dispatch is more flexible and powerful than the Python class system. - Julia structures may have exactly one abstract supertype, whereas Python classes can inherit from one or more (abstract or concrete) superclasses.
- The logical Julia program structure (Packages and Modules) is independent of the file structure (
include
for additional files), whereas the Python code structure is defined by directories (Packages) and files (Modules). - The ternary operator
x > 0 ? 1 : -1
in Julia corresponds to a conditional expression in Python1 if x > 0 else -1
. - In Julia the
@
symbol refers to a macro, whereas in Python it refers to a decorator. - Exception handling in Julia is done using
try
—catch
—finally
, instead oftry
—except
—finally
. In contrast to Python, it is not recommended to use exception handling as part of the normal workflow in Julia (compared with Python, Julia is faster at ordinary control flow but slower at exception-catching). - In Julia loops are fast, there is no need to write “vectorized” code for performance reasons.
- Be careful with non-constant global variables in Julia, especially in tight loops. Since you can write close-to-metal code in Julia (unlike Python), the effect of globals can be drastic (seePerformance Tips).
- In Julia, rounding and truncation are explicit. Python’s
int(3.7)
should befloor(Int, 3.7)
orInt(floor(3.7))
and is distinguished fromround(Int, 3.7)
.floor(x)
andround(x)
on their own return an integer value of the same type asx
rather than always returningInt
. - In Julia, parsing is explicit. Python’s
float("3.7")
would beparse(Float64, "3.7")
in Julia. - In Python, the majority of values can be used in logical contexts (e.g.
if "a":
means the following block is executed, andif "":
means it is not). In Julia, you need explicit conversion toBool
(e.g.if "a"
throws an exception). If you want to test for a non-empty string in Julia, you would explicitly writeif !isempty("")
. Perhaps surprisingly, in Pythonif "False"
andbool("False")
both evaluate toTrue
(because"False"
is a non-empty string); in Julia,parse(Bool, "false")
returnsfalse
. - In Julia, a new local scope is introduced by most code blocks, including loops and
try
—catch
—finally
. Note that comprehensions (list, generator, etc.) introduce a new local scope both in Python and Julia, whereasif
blocks do not introduce a new local scope in both languages.
Noteworthy differences from Python
How is string concatenation different in Julia compared to Python?
Noteworthy differences from Python
- Julia’s
for
,if
,while
, etc. blocks are terminated by theend
keyword. Indentation level is not significant as it is in Python. Unlike Python, Julia has nopass
keyword. - Strings are denoted by double quotation marks (
"text"
) in Julia (with three double quotation marks for multi-line strings), whereas in Python they can be denoted either by single ('text'
) or double quotation marks ("text"
). Single quotation marks are used for characters in Julia ('c'
). - String concatenation is done with
*
in Julia, not+
like in Python. Analogously, string repetition is done with^
, not*
. Implicit string concatenation of string literals like in Python (e.g.'ab' 'cd' == 'abcd'
) is not done in Julia. - Python Lists—flexible but slow—correspond to the Julia
Vector{Any}
type or more generallyVector{T}
whereT
is some non-concrete element type. “Fast” arrays like NumPy arrays that store elements in-place (i.e.,dtype
isnp.float64
,[('f1', np.uint64), ('f2', np.int32)]
, etc.) can be represented byArray{T}
whereT
is a concrete, immutable element type. This includes built-in types likeFloat64
,Int32
,Int64
but also more complex types likeTuple{UInt64,Float64}
and many user-defined types as well. - In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.
- Julia’s slice indexing includes the last element, unlike in Python.
a[2:3]
in Julia isa[1:3]
in Python. - Unlike Python, Julia allowsAbstractArrays with arbitrary indexes. Python’s special interpretation of negative indexing,
a[-1]
anda[-2]
, should be writtena[end]
anda[end-1]
in Julia. - Julia requires
end
for indexing until the last element.x[1:]
in Python is equivalent tox[2:end]
in Julia. - In Julia,
:
before any object creates aSymbol
or_quotes_an expression; so,x[:5]
is same asx[5]
. If you want to get the firstn
elements of an array, then use range indexing. - Julia’s range indexing has the format of
x[start:step:stop]
, whereas Python’s format isx[start:(stop+1):step]
. Hence,x[0:10:2]
in Python is equivalent tox[1:2:10]
in Julia. Similarly,x[::-1]
in Python, which refers to the reversed array, is equivalent tox[end:-1:1]
in Julia. - In Julia, ranges can be constructed independently as
start:step:stop
, the same syntax it uses in array-indexing. Therange
function is also supported. - In Julia, indexing a matrix with arrays like
X[[1,2], [1,3]]
refers to a sub-matrix that contains the intersections of the first and second rows with the first and third columns. In Python,X[[1,2], [1,3]]
refers to a vector that contains the values of cell[1,1]
and[2,3]
in the matrix.X[[1,2], [1,3]]
in Julia is equivalent withX[np.ix_([0,1],[0,2])]
in Python.X[[0,1], [0,2]]
in Python is equivalent withX[[CartesianIndex(1,1), CartesianIndex(2,3)]]
in Julia. - Julia has no line continuation syntax: if, at the end of a line, the input so far is a complete expression, it is considered done; otherwise the input continues. One way to force an expression to continue is to wrap it in parentheses.
- Julia arrays are column-major (Fortran-ordered) whereas NumPy arrays are row-major (C-ordered) by default. To get optimal performance when looping over arrays, the order of the loops should be reversed in Julia relative to NumPy (seerelevant section of Performance Tips).
- Julia’s updating operators (e.g.
+=
,-=
, …) are_not in-place_whereas NumPy’s are. This meansA = [1, 1]; B = A; B += [3, 3]
doesn’t change values inA
, it rather rebinds the nameB
to the result of the right-hand sideB = B + 3
, which is a new array. For in-place operation, useB .+= 3
(see alsodot operators), explicit loops, orInplaceOps.jl
. - Julia evaluates default values of function arguments every time the method is invoked, unlike in Python where the default values are evaluated only once when the function is defined. For example, the function
f(x=rand()) = x
returns a new random number every time it is invoked without argument. On the other hand, the functiong(x=[1,2]) = push!(x,3)
returns[1,2,3]
every time it is called asg()
. - In Julia, keyword arguments must be passed using keywords, unlike Python in which it is usually possible to pass them positionally. Attempting to pass a keyword argument positionally alters the method signature leading to a
MethodError
or calling of the wrong method. - In Julia
%
is the remainder operator, whereas in Python it is the modulus. - In Julia, the commonly used
Int
type corresponds to the machine integer type (Int32
orInt64
), unlike in Python, whereint
is an arbitrary length integer. This means in Julia theInt
type will overflow, such that2^64 == 0
. If you need larger values use another appropriate type, such asInt128
,BigInt
or a floating point type likeFloat64
. - The imaginary unit
sqrt(-1)
is represented in Julia asim
, notj
as in Python. - In Julia, the exponentiation operator is
^
, not**
as in Python. - Julia uses
nothing
of typeNothing
to represent a null value, whereas Python usesNone
of typeNoneType
. - In Julia, the standard operators over a matrix type are matrix operations, whereas, in Python, the standard operators are element-wise operations. When both
A
andB
are matrices,A * B
in Julia performs matrix multiplication, not element-wise multiplication as in Python.A * B
in Julia is equivalent withA @ B
in Python, whereasA * B
in Python is equivalent withA .* B
in Julia. - The adjoint operator
'
in Julia returns an adjoint of a vector (a lazy representation of row vector), whereas the transpose operator.T
over a vector in Python returns the original vector (non-op). - In Julia, a function may contain multiple concrete implementations (called_methods_), which are selected via multiple dispatch based on the types of all arguments to the call, as compared to functions in Python, which have a single implementation and no polymorphism (as opposed to Python method calls which use a different syntax and allows dispatch on the receiver of the method).
- There are no classes in Julia. Instead there are structures (mutable or immutable), containing data but no methods.
- Calling a method of a class instance in Python (
x = MyClass(*args); x.f(y)
) corresponds to a function call in Julia, e.g.x = MyType(args...); f(x, y)
. In general, multiple dispatch is more flexible and powerful than the Python class system. - Julia structures may have exactly one abstract supertype, whereas Python classes can inherit from one or more (abstract or concrete) superclasses.
- The logical Julia program structure (Packages and Modules) is independent of the file structure (
include
for additional files), whereas the Python code structure is defined by directories (Packages) and files (Modules). - The ternary operator
x > 0 ? 1 : -1
in Julia corresponds to a conditional expression in Python1 if x > 0 else -1
. - In Julia the
@
symbol refers to a macro, whereas in Python it refers to a decorator. - Exception handling in Julia is done using
try
—catch
—finally
, instead oftry
—except
—finally
. In contrast to Python, it is not recommended to use exception handling as part of the normal workflow in Julia (compared with Python, Julia is faster at ordinary control flow but slower at exception-catching). - In Julia loops are fast, there is no need to write “vectorized” code for performance reasons.
- Be careful with non-constant global variables in Julia, especially in tight loops. Since you can write close-to-metal code in Julia (unlike Python), the effect of globals can be drastic (seePerformance Tips).
- In Julia, rounding and truncation are explicit. Python’s
int(3.7)
should befloor(Int, 3.7)
orInt(floor(3.7))
and is distinguished fromround(Int, 3.7)
.floor(x)
andround(x)
on their own return an integer value of the same type asx
rather than always returningInt
. - In Julia, parsing is explicit. Python’s
float("3.7")
would beparse(Float64, "3.7")
in Julia. - In Python, the majority of values can be used in logical contexts (e.g.
if "a":
means the following block is executed, andif "":
means it is not). In Julia, you need explicit conversion toBool
(e.g.if "a"
throws an exception). If you want to test for a non-empty string in Julia, you would explicitly writeif !isempty("")
. Perhaps surprisingly, in Pythonif "False"
andbool("False")
both evaluate toTrue
(because"False"
is a non-empty string); in Julia,parse(Bool, "false")
returnsfalse
. - In Julia, a new local scope is introduced by most code blocks, including loops and
try
—catch
—finally
. Note that comprehensions (list, generator, etc.) introduce a new local scope both in Python and Julia, whereasif
blocks do not introduce a new local scope in both languages.
Noteworthy differences from Python
How is string repetition different in Julia compared to Python?
Noteworthy differences from Python
- Julia’s
for
,if
,while
, etc. blocks are terminated by theend
keyword. Indentation level is not significant as it is in Python. Unlike Python, Julia has nopass
keyword. - Strings are denoted by double quotation marks (
"text"
) in Julia (with three double quotation marks for multi-line strings), whereas in Python they can be denoted either by single ('text'
) or double quotation marks ("text"
). Single quotation marks are used for characters in Julia ('c'
). - String concatenation is done with
*
in Julia, not+
like in Python. Analogously, string repetition is done with^
, not*
. Implicit string concatenation of string literals like in Python (e.g.'ab' 'cd' == 'abcd'
) is not done in Julia. - Python Lists—flexible but slow—correspond to the Julia
Vector{Any}
type or more generallyVector{T}
whereT
is some non-concrete element type. “Fast” arrays like NumPy arrays that store elements in-place (i.e.,dtype
isnp.float64
,[('f1', np.uint64), ('f2', np.int32)]
, etc.) can be represented byArray{T}
whereT
is a concrete, immutable element type. This includes built-in types likeFloat64
,Int32
,Int64
but also more complex types likeTuple{UInt64,Float64}
and many user-defined types as well. - In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.
- Julia’s slice indexing includes the last element, unlike in Python.
a[2:3]
in Julia isa[1:3]
in Python. - Unlike Python, Julia allowsAbstractArrays with arbitrary indexes. Python’s special interpretation of negative indexing,
a[-1]
anda[-2]
, should be writtena[end]
anda[end-1]
in Julia. - Julia requires
end
for indexing until the last element.x[1:]
in Python is equivalent tox[2:end]
in Julia. - In Julia,
:
before any object creates aSymbol
or_quotes_an expression; so,x[:5]
is same asx[5]
. If you want to get the firstn
elements of an array, then use range indexing. - Julia’s range indexing has the format of
x[start:step:stop]
, whereas Python’s format isx[start:(stop+1):step]
. Hence,x[0:10:2]
in Python is equivalent tox[1:2:10]
in Julia. Similarly,x[::-1]
in Python, which refers to the reversed array, is equivalent tox[end:-1:1]
in Julia. - In Julia, ranges can be constructed independently as
start:step:stop
, the same syntax it uses in array-indexing. Therange
function is also supported. - In Julia, indexing a matrix with arrays like
X[[1,2], [1,3]]
refers to a sub-matrix that contains the intersections of the first and second rows with the first and third columns. In Python,X[[1,2], [1,3]]
refers to a vector that contains the values of cell[1,1]
and[2,3]
in the matrix.X[[1,2], [1,3]]
in Julia is equivalent withX[np.ix_([0,1],[0,2])]
in Python.X[[0,1], [0,2]]
in Python is equivalent withX[[CartesianIndex(1,1), CartesianIndex(2,3)]]
in Julia. - Julia has no line continuation syntax: if, at the end of a line, the input so far is a complete expression, it is considered done; otherwise the input continues. One way to force an expression to continue is to wrap it in parentheses.
- Julia arrays are column-major (Fortran-ordered) whereas NumPy arrays are row-major (C-ordered) by default. To get optimal performance when looping over arrays, the order of the loops should be reversed in Julia relative to NumPy (seerelevant section of Performance Tips).
- Julia’s updating operators (e.g.
+=
,-=
, …) are_not in-place_whereas NumPy’s are. This meansA = [1, 1]; B = A; B += [3, 3]
doesn’t change values inA
, it rather rebinds the nameB
to the result of the right-hand sideB = B + 3
, which is a new array. For in-place operation, useB .+= 3
(see alsodot operators), explicit loops, orInplaceOps.jl
. - Julia evaluates default values of function arguments every time the method is invoked, unlike in Python where the default values are evaluated only once when the function is defined. For example, the function
f(x=rand()) = x
returns a new random number every time it is invoked without argument. On the other hand, the functiong(x=[1,2]) = push!(x,3)
returns[1,2,3]
every time it is called asg()
. - In Julia, keyword arguments must be passed using keywords, unlike Python in which it is usually possible to pass them positionally. Attempting to pass a keyword argument positionally alters the method signature leading to a
MethodError
or calling of the wrong method. - In Julia
%
is the remainder operator, whereas in Python it is the modulus. - In Julia, the commonly used
Int
type corresponds to the machine integer type (Int32
orInt64
), unlike in Python, whereint
is an arbitrary length integer. This means in Julia theInt
type will overflow, such that2^64 == 0
. If you need larger values use another appropriate type, such asInt128
,BigInt
or a floating point type likeFloat64
. - The imaginary unit
sqrt(-1)
is represented in Julia asim
, notj
as in Python. - In Julia, the exponentiation operator is
^
, not**
as in Python. - Julia uses
nothing
of typeNothing
to represent a null value, whereas Python usesNone
of typeNoneType
. - In Julia, the standard operators over a matrix type are matrix operations, whereas, in Python, the standard operators are element-wise operations. When both
A
andB
are matrices,A * B
in Julia performs matrix multiplication, not element-wise multiplication as in Python.A * B
in Julia is equivalent withA @ B
in Python, whereasA * B
in Python is equivalent withA .* B
in Julia. - The adjoint operator
'
in Julia returns an adjoint of a vector (a lazy representation of row vector), whereas the transpose operator.T
over a vector in Python returns the original vector (non-op). - In Julia, a function may contain multiple concrete implementations (called_methods_), which are selected via multiple dispatch based on the types of all arguments to the call, as compared to functions in Python, which have a single implementation and no polymorphism (as opposed to Python method calls which use a different syntax and allows dispatch on the receiver of the method).
- There are no classes in Julia. Instead there are structures (mutable or immutable), containing data but no methods.
- Calling a method of a class instance in Python (
x = MyClass(*args); x.f(y)
) corresponds to a function call in Julia, e.g.x = MyType(args...); f(x, y)
. In general, multiple dispatch is more flexible and powerful than the Python class system. - Julia structures may have exactly one abstract supertype, whereas Python classes can inherit from one or more (abstract or concrete) superclasses.
- The logical Julia program structure (Packages and Modules) is independent of the file structure (
include
for additional files), whereas the Python code structure is defined by directories (Packages) and files (Modules). - The ternary operator
x > 0 ? 1 : -1
in Julia corresponds to a conditional expression in Python1 if x > 0 else -1
. - In Julia the
@
symbol refers to a macro, whereas in Python it refers to a decorator. - Exception handling in Julia is done using
try
—catch
—finally
, instead oftry
—except
—finally
. In contrast to Python, it is not recommended to use exception handling as part of the normal workflow in Julia (compared with Python, Julia is faster at ordinary control flow but slower at exception-catching). - In Julia loops are fast, there is no need to write “vectorized” code for performance reasons.
- Be careful with non-constant global variables in Julia, especially in tight loops. Since you can write close-to-metal code in Julia (unlike Python), the effect of globals can be drastic (seePerformance Tips).
- In Julia, rounding and truncation are explicit. Python’s
int(3.7)
should befloor(Int, 3.7)
orInt(floor(3.7))
and is distinguished fromround(Int, 3.7)
.floor(x)
andround(x)
on their own return an integer value of the same type asx
rather than always returningInt
. - In Julia, parsing is explicit. Python’s
float("3.7")
would beparse(Float64, "3.7")
in Julia. - In Python, the majority of values can be used in logical contexts (e.g.
if "a":
means the following block is executed, andif "":
means it is not). In Julia, you need explicit conversion toBool
(e.g.if "a"
throws an exception). If you want to test for a non-empty string in Julia, you would explicitly writeif !isempty("")
. Perhaps surprisingly, in Pythonif "False"
andbool("False")
both evaluate toTrue
(because"False"
is a non-empty string); in Julia,parse(Bool, "false")
returnsfalse
. - In Julia, a new local scope is introduced by most code blocks, including loops and
try
—catch
—finally
. Note that comprehensions (list, generator, etc.) introduce a new local scope both in Python and Julia, whereasif
blocks do not introduce a new local scope in both languages.
Noteworthy differences from Python
How do Python’s lists correspond to in Julia?
Noteworthy differences from Python
- Julia’s
for
,if
,while
, etc. blocks are terminated by theend
keyword. Indentation level is not significant as it is in Python. Unlike Python, Julia has nopass
keyword. - Strings are denoted by double quotation marks (
"text"
) in Julia (with three double quotation marks for multi-line strings), whereas in Python they can be denoted either by single ('text'
) or double quotation marks ("text"
). Single quotation marks are used for characters in Julia ('c'
). - String concatenation is done with
*
in Julia, not+
like in Python. Analogously, string repetition is done with^
, not*
. Implicit string concatenation of string literals like in Python (e.g.'ab' 'cd' == 'abcd'
) is not done in Julia. - Python Lists—flexible but slow—correspond to the Julia
Vector{Any}
type or more generallyVector{T}
whereT
is some non-concrete element type. “Fast” arrays like NumPy arrays that store elements in-place (i.e.,dtype
isnp.float64
,[('f1', np.uint64), ('f2', np.int32)]
, etc.) can be represented byArray{T}
whereT
is a concrete, immutable element type. This includes built-in types likeFloat64
,Int32
,Int64
but also more complex types likeTuple{UInt64,Float64}
and many user-defined types as well. - In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.
- Julia’s slice indexing includes the last element, unlike in Python.
a[2:3]
in Julia isa[1:3]
in Python. - Unlike Python, Julia allowsAbstractArrays with arbitrary indexes. Python’s special interpretation of negative indexing,
a[-1]
anda[-2]
, should be writtena[end]
anda[end-1]
in Julia. - Julia requires
end
for indexing until the last element.x[1:]
in Python is equivalent tox[2:end]
in Julia. - In Julia,
:
before any object creates aSymbol
or_quotes_an expression; so,x[:5]
is same asx[5]
. If you want to get the firstn
elements of an array, then use range indexing. - Julia’s range indexing has the format of
x[start:step:stop]
, whereas Python’s format isx[start:(stop+1):step]
. Hence,x[0:10:2]
in Python is equivalent tox[1:2:10]
in Julia. Similarly,x[::-1]
in Python, which refers to the reversed array, is equivalent tox[end:-1:1]
in Julia. - In Julia, ranges can be constructed independently as
start:step:stop
, the same syntax it uses in array-indexing. Therange
function is also supported. - In Julia, indexing a matrix with arrays like
X[[1,2], [1,3]]
refers to a sub-matrix that contains the intersections of the first and second rows with the first and third columns. In Python,X[[1,2], [1,3]]
refers to a vector that contains the values of cell[1,1]
and[2,3]
in the matrix.X[[1,2], [1,3]]
in Julia is equivalent withX[np.ix_([0,1],[0,2])]
in Python.X[[0,1], [0,2]]
in Python is equivalent withX[[CartesianIndex(1,1), CartesianIndex(2,3)]]
in Julia. - Julia has no line continuation syntax: if, at the end of a line, the input so far is a complete expression, it is considered done; otherwise the input continues. One way to force an expression to continue is to wrap it in parentheses.
- Julia arrays are column-major (Fortran-ordered) whereas NumPy arrays are row-major (C-ordered) by default. To get optimal performance when looping over arrays, the order of the loops should be reversed in Julia relative to NumPy (seerelevant section of Performance Tips).
- Julia’s updating operators (e.g.
+=
,-=
, …) are_not in-place_whereas NumPy’s are. This meansA = [1, 1]; B = A; B += [3, 3]
doesn’t change values inA
, it rather rebinds the nameB
to the result of the right-hand sideB = B + 3
, which is a new array. For in-place operation, useB .+= 3
(see alsodot operators), explicit loops, orInplaceOps.jl
. - Julia evaluates default values of function arguments every time the method is invoked, unlike in Python where the default values are evaluated only once when the function is defined. For example, the function
f(x=rand()) = x
returns a new random number every time it is invoked without argument. On the other hand, the functiong(x=[1,2]) = push!(x,3)
returns[1,2,3]
every time it is called asg()
. - In Julia, keyword arguments must be passed using keywords, unlike Python in which it is usually possible to pass them positionally. Attempting to pass a keyword argument positionally alters the method signature leading to a
MethodError
or calling of the wrong method. - In Julia
%
is the remainder operator, whereas in Python it is the modulus. - In Julia, the commonly used
Int
type corresponds to the machine integer type (Int32
orInt64
), unlike in Python, whereint
is an arbitrary length integer. This means in Julia theInt
type will overflow, such that2^64 == 0
. If you need larger values use another appropriate type, such asInt128
,BigInt
or a floating point type likeFloat64
. - The imaginary unit
sqrt(-1)
is represented in Julia asim
, notj
as in Python. - In Julia, the exponentiation operator is
^
, not**
as in Python. - Julia uses
nothing
of typeNothing
to represent a null value, whereas Python usesNone
of typeNoneType
. - In Julia, the standard operators over a matrix type are matrix operations, whereas, in Python, the standard operators are element-wise operations. When both
A
andB
are matrices,A * B
in Julia performs matrix multiplication, not element-wise multiplication as in Python.A * B
in Julia is equivalent withA @ B
in Python, whereasA * B
in Python is equivalent withA .* B
in Julia. - The adjoint operator
'
in Julia returns an adjoint of a vector (a lazy representation of row vector), whereas the transpose operator.T
over a vector in Python returns the original vector (non-op). - In Julia, a function may contain multiple concrete implementations (called_methods_), which are selected via multiple dispatch based on the types of all arguments to the call, as compared to functions in Python, which have a single implementation and no polymorphism (as opposed to Python method calls which use a different syntax and allows dispatch on the receiver of the method).
- There are no classes in Julia. Instead there are structures (mutable or immutable), containing data but no methods.
- Calling a method of a class instance in Python (
x = MyClass(*args); x.f(y)
) corresponds to a function call in Julia, e.g.x = MyType(args...); f(x, y)
. In general, multiple dispatch is more flexible and powerful than the Python class system. - Julia structures may have exactly one abstract supertype, whereas Python classes can inherit from one or more (abstract or concrete) superclasses.
- The logical Julia program structure (Packages and Modules) is independent of the file structure (
include
for additional files), whereas the Python code structure is defined by directories (Packages) and files (Modules). - The ternary operator
x > 0 ? 1 : -1
in Julia corresponds to a conditional expression in Python1 if x > 0 else -1
. - In Julia the
@
symbol refers to a macro, whereas in Python it refers to a decorator. - Exception handling in Julia is done using
try
—catch
—finally
, instead oftry
—except
—finally
. In contrast to Python, it is not recommended to use exception handling as part of the normal workflow in Julia (compared with Python, Julia is faster at ordinary control flow but slower at exception-catching). - In Julia loops are fast, there is no need to write “vectorized” code for performance reasons.
- Be careful with non-constant global variables in Julia, especially in tight loops. Since you can write close-to-metal code in Julia (unlike Python), the effect of globals can be drastic (seePerformance Tips).
- In Julia, rounding and truncation are explicit. Python’s
int(3.7)
should befloor(Int, 3.7)
orInt(floor(3.7))
and is distinguished fromround(Int, 3.7)
.floor(x)
andround(x)
on their own return an integer value of the same type asx
rather than always returningInt
. - In Julia, parsing is explicit. Python’s
float("3.7")
would beparse(Float64, "3.7")
in Julia. - In Python, the majority of values can be used in logical contexts (e.g.
if "a":
means the following block is executed, andif "":
means it is not). In Julia, you need explicit conversion toBool
(e.g.if "a"
throws an exception). If you want to test for a non-empty string in Julia, you would explicitly writeif !isempty("")
. Perhaps surprisingly, in Pythonif "False"
andbool("False")
both evaluate toTrue
(because"False"
is a non-empty string); in Julia,parse(Bool, "false")
returnsfalse
. - In Julia, a new local scope is introduced by most code blocks, including loops and
try
—catch
—finally
. Note that comprehensions (list, generator, etc.) introduce a new local scope both in Python and Julia, whereasif
blocks do not introduce a new local scope in both languages.
Noteworthy differences from Python
What do Python’s fast numpy arrays correspond to in Julia?
Noteworthy differences from Python
- Julia’s
for
,if
,while
, etc. blocks are terminated by theend
keyword. Indentation level is not significant as it is in Python. Unlike Python, Julia has nopass
keyword. - Strings are denoted by double quotation marks (
"text"
) in Julia (with three double quotation marks for multi-line strings), whereas in Python they can be denoted either by single ('text'
) or double quotation marks ("text"
). Single quotation marks are used for characters in Julia ('c'
). - String concatenation is done with
*
in Julia, not+
like in Python. Analogously, string repetition is done with^
, not*
. Implicit string concatenation of string literals like in Python (e.g.'ab' 'cd' == 'abcd'
) is not done in Julia. - Python Lists—flexible but slow—correspond to the Julia
Vector{Any}
type or more generallyVector{T}
whereT
is some non-concrete element type. “Fast” arrays like NumPy arrays that store elements in-place (i.e.,dtype
isnp.float64
,[('f1', np.uint64), ('f2', np.int32)]
, etc.) can be represented byArray{T}
whereT
is a concrete, immutable element type. This includes built-in types likeFloat64
,Int32
,Int64
but also more complex types likeTuple{UInt64,Float64}
and many user-defined types as well. - In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.
- Julia’s slice indexing includes the last element, unlike in Python.
a[2:3]
in Julia isa[1:3]
in Python. - Unlike Python, Julia allowsAbstractArrays with arbitrary indexes. Python’s special interpretation of negative indexing,
a[-1]
anda[-2]
, should be writtena[end]
anda[end-1]
in Julia. - Julia requires
end
for indexing until the last element.x[1:]
in Python is equivalent tox[2:end]
in Julia. - In Julia,
:
before any object creates aSymbol
or_quotes_an expression; so,x[:5]
is same asx[5]
. If you want to get the firstn
elements of an array, then use range indexing. - Julia’s range indexing has the format of
x[start:step:stop]
, whereas Python’s format isx[start:(stop+1):step]
. Hence,x[0:10:2]
in Python is equivalent tox[1:2:10]
in Julia. Similarly,x[::-1]
in Python, which refers to the reversed array, is equivalent tox[end:-1:1]
in Julia. - In Julia, ranges can be constructed independently as
start:step:stop
, the same syntax it uses in array-indexing. Therange
function is also supported. - In Julia, indexing a matrix with arrays like
X[[1,2], [1,3]]
refers to a sub-matrix that contains the intersections of the first and second rows with the first and third columns. In Python,X[[1,2], [1,3]]
refers to a vector that contains the values of cell[1,1]
and[2,3]
in the matrix.X[[1,2], [1,3]]
in Julia is equivalent withX[np.ix_([0,1],[0,2])]
in Python.X[[0,1], [0,2]]
in Python is equivalent withX[[CartesianIndex(1,1), CartesianIndex(2,3)]]
in Julia. - Julia has no line continuation syntax: if, at the end of a line, the input so far is a complete expression, it is considered done; otherwise the input continues. One way to force an expression to continue is to wrap it in parentheses.
- Julia arrays are column-major (Fortran-ordered) whereas NumPy arrays are row-major (C-ordered) by default. To get optimal performance when looping over arrays, the order of the loops should be reversed in Julia relative to NumPy (seerelevant section of Performance Tips).
- Julia’s updating operators (e.g.
+=
,-=
, …) are_not in-place_whereas NumPy’s are. This meansA = [1, 1]; B = A; B += [3, 3]
doesn’t change values inA
, it rather rebinds the nameB
to the result of the right-hand sideB = B + 3
, which is a new array. For in-place operation, useB .+= 3
(see alsodot operators), explicit loops, orInplaceOps.jl
. - Julia evaluates default values of function arguments every time the method is invoked, unlike in Python where the default values are evaluated only once when the function is defined. For example, the function
f(x=rand()) = x
returns a new random number every time it is invoked without argument. On the other hand, the functiong(x=[1,2]) = push!(x,3)
returns[1,2,3]
every time it is called asg()
. - In Julia, keyword arguments must be passed using keywords, unlike Python in which it is usually possible to pass them positionally. Attempting to pass a keyword argument positionally alters the method signature leading to a
MethodError
or calling of the wrong method. - In Julia
%
is the remainder operator, whereas in Python it is the modulus. - In Julia, the commonly used
Int
type corresponds to the machine integer type (Int32
orInt64
), unlike in Python, whereint
is an arbitrary length integer. This means in Julia theInt
type will overflow, such that2^64 == 0
. If you need larger values use another appropriate type, such asInt128
,BigInt
or a floating point type likeFloat64
. - The imaginary unit
sqrt(-1)
is represented in Julia asim
, notj
as in Python. - In Julia, the exponentiation operator is
^
, not**
as in Python. - Julia uses
nothing
of typeNothing
to represent a null value, whereas Python usesNone
of typeNoneType
. - In Julia, the standard operators over a matrix type are matrix operations, whereas, in Python, the standard operators are element-wise operations. When both
A
andB
are matrices,A * B
in Julia performs matrix multiplication, not element-wise multiplication as in Python.A * B
in Julia is equivalent withA @ B
in Python, whereasA * B
in Python is equivalent withA .* B
in Julia. - The adjoint operator
'
in Julia returns an adjoint of a vector (a lazy representation of row vector), whereas the transpose operator.T
over a vector in Python returns the original vector (non-op). - In Julia, a function may contain multiple concrete implementations (called_methods_), which are selected via multiple dispatch based on the types of all arguments to the call, as compared to functions in Python, which have a single implementation and no polymorphism (as opposed to Python method calls which use a different syntax and allows dispatch on the receiver of the method).
- There are no classes in Julia. Instead there are structures (mutable or immutable), containing data but no methods.
- Calling a method of a class instance in Python (
x = MyClass(*args); x.f(y)
) corresponds to a function call in Julia, e.g.x = MyType(args...); f(x, y)
. In general, multiple dispatch is more flexible and powerful than the Python class system. - Julia structures may have exactly one abstract supertype, whereas Python classes can inherit from one or more (abstract or concrete) superclasses.
- The logical Julia program structure (Packages and Modules) is independent of the file structure (
include
for additional files), whereas the Python code structure is defined by directories (Packages) and files (Modules). - The ternary operator
x > 0 ? 1 : -1
in Julia corresponds to a conditional expression in Python1 if x > 0 else -1
. - In Julia the
@
symbol refers to a macro, whereas in Python it refers to a decorator. - Exception handling in Julia is done using
try
—catch
—finally
, instead oftry
—except
—finally
. In contrast to Python, it is not recommended to use exception handling as part of the normal workflow in Julia (compared with Python, Julia is faster at ordinary control flow but slower at exception-catching). - In Julia loops are fast, there is no need to write “vectorized” code for performance reasons.
- Be careful with non-constant global variables in Julia, especially in tight loops. Since you can write close-to-metal code in Julia (unlike Python), the effect of globals can be drastic (seePerformance Tips).
- In Julia, rounding and truncation are explicit. Python’s
int(3.7)
should befloor(Int, 3.7)
orInt(floor(3.7))
and is distinguished fromround(Int, 3.7)
.floor(x)
andround(x)
on their own return an integer value of the same type asx
rather than always returningInt
. - In Julia, parsing is explicit. Python’s
float("3.7")
would beparse(Float64, "3.7")
in Julia. - In Python, the majority of values can be used in logical contexts (e.g.
if "a":
means the following block is executed, andif "":
means it is not). In Julia, you need explicit conversion toBool
(e.g.if "a"
throws an exception). If you want to test for a non-empty string in Julia, you would explicitly writeif !isempty("")
. Perhaps surprisingly, in Pythonif "False"
andbool("False")
both evaluate toTrue
(because"False"
is a non-empty string); in Julia,parse(Bool, "false")
returnsfalse
. - In Julia, a new local scope is introduced by most code blocks, including loops and
try
—catch
—finally
. Note that comprehensions (list, generator, etc.) introduce a new local scope both in Python and Julia, whereasif
blocks do not introduce a new local scope in both languages.
Noteworthy differences from Python
How does Julia’s indexing differ from Python’s?
Noteworthy differences from Python
- Julia’s
for
,if
,while
, etc. blocks are terminated by theend
keyword. Indentation level is not significant as it is in Python. Unlike Python, Julia has nopass
keyword. - Strings are denoted by double quotation marks (
"text"
) in Julia (with three double quotation marks for multi-line strings), whereas in Python they can be denoted either by single ('text'
) or double quotation marks ("text"
). Single quotation marks are used for characters in Julia ('c'
). - String concatenation is done with
*
in Julia, not+
like in Python. Analogously, string repetition is done with^
, not*
. Implicit string concatenation of string literals like in Python (e.g.'ab' 'cd' == 'abcd'
) is not done in Julia. - Python Lists—flexible but slow—correspond to the Julia
Vector{Any}
type or more generallyVector{T}
whereT
is some non-concrete element type. “Fast” arrays like NumPy arrays that store elements in-place (i.e.,dtype
isnp.float64
,[('f1', np.uint64), ('f2', np.int32)]
, etc.) can be represented byArray{T}
whereT
is a concrete, immutable element type. This includes built-in types likeFloat64
,Int32
,Int64
but also more complex types likeTuple{UInt64,Float64}
and many user-defined types as well. - In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.
- Julia’s slice indexing includes the last element, unlike in Python.
a[2:3]
in Julia isa[1:3]
in Python. - Unlike Python, Julia allowsAbstractArrays with arbitrary indexes. Python’s special interpretation of negative indexing,
a[-1]
anda[-2]
, should be writtena[end]
anda[end-1]
in Julia. - Julia requires
end
for indexing until the last element.x[1:]
in Python is equivalent tox[2:end]
in Julia. - In Julia,
:
before any object creates aSymbol
or_quotes_an expression; so,x[:5]
is same asx[5]
. If you want to get the firstn
elements of an array, then use range indexing. - Julia’s range indexing has the format of
x[start:step:stop]
, whereas Python’s format isx[start:(stop+1):step]
. Hence,x[0:10:2]
in Python is equivalent tox[1:2:10]
in Julia. Similarly,x[::-1]
in Python, which refers to the reversed array, is equivalent tox[end:-1:1]
in Julia. - In Julia, ranges can be constructed independently as
start:step:stop
, the same syntax it uses in array-indexing. Therange
function is also supported. - In Julia, indexing a matrix with arrays like
X[[1,2], [1,3]]
refers to a sub-matrix that contains the intersections of the first and second rows with the first and third columns. In Python,X[[1,2], [1,3]]
refers to a vector that contains the values of cell[1,1]
and[2,3]
in the matrix.X[[1,2], [1,3]]
in Julia is equivalent withX[np.ix_([0,1],[0,2])]
in Python.X[[0,1], [0,2]]
in Python is equivalent withX[[CartesianIndex(1,1), CartesianIndex(2,3)]]
in Julia. - Julia has no line continuation syntax: if, at the end of a line, the input so far is a complete expression, it is considered done; otherwise the input continues. One way to force an expression to continue is to wrap it in parentheses.
- Julia arrays are column-major (Fortran-ordered) whereas NumPy arrays are row-major (C-ordered) by default. To get optimal performance when looping over arrays, the order of the loops should be reversed in Julia relative to NumPy (seerelevant section of Performance Tips).
- Julia’s updating operators (e.g.
+=
,-=
, …) are_not in-place_whereas NumPy’s are. This meansA = [1, 1]; B = A; B += [3, 3]
doesn’t change values inA
, it rather rebinds the nameB
to the result of the right-hand sideB = B + 3
, which is a new array. For in-place operation, useB .+= 3
(see alsodot operators), explicit loops, orInplaceOps.jl
. - Julia evaluates default values of function arguments every time the method is invoked, unlike in Python where the default values are evaluated only once when the function is defined. For example, the function
f(x=rand()) = x
returns a new random number every time it is invoked without argument. On the other hand, the functiong(x=[1,2]) = push!(x,3)
returns[1,2,3]
every time it is called asg()
. - In Julia, keyword arguments must be passed using keywords, unlike Python in which it is usually possible to pass them positionally. Attempting to pass a keyword argument positionally alters the method signature leading to a
MethodError
or calling of the wrong method. - In Julia
%
is the remainder operator, whereas in Python it is the modulus. - In Julia, the commonly used
Int
type corresponds to the machine integer type (Int32
orInt64
), unlike in Python, whereint
is an arbitrary length integer. This means in Julia theInt
type will overflow, such that2^64 == 0
. If you need larger values use another appropriate type, such asInt128
,BigInt
or a floating point type likeFloat64
. - The imaginary unit
sqrt(-1)
is represented in Julia asim
, notj
as in Python. - In Julia, the exponentiation operator is
^
, not**
as in Python. - Julia uses
nothing
of typeNothing
to represent a null value, whereas Python usesNone
of typeNoneType
. - In Julia, the standard operators over a matrix type are matrix operations, whereas, in Python, the standard operators are element-wise operations. When both
A
andB
are matrices,A * B
in Julia performs matrix multiplication, not element-wise multiplication as in Python.A * B
in Julia is equivalent withA @ B
in Python, whereasA * B
in Python is equivalent withA .* B
in Julia. - The adjoint operator
'
in Julia returns an adjoint of a vector (a lazy representation of row vector), whereas the transpose operator.T
over a vector in Python returns the original vector (non-op). - In Julia, a function may contain multiple concrete implementations (called_methods_), which are selected via multiple dispatch based on the types of all arguments to the call, as compared to functions in Python, which have a single implementation and no polymorphism (as opposed to Python method calls which use a different syntax and allows dispatch on the receiver of the method).
- There are no classes in Julia. Instead there are structures (mutable or immutable), containing data but no methods.
- Calling a method of a class instance in Python (
x = MyClass(*args); x.f(y)
) corresponds to a function call in Julia, e.g.x = MyType(args...); f(x, y)
. In general, multiple dispatch is more flexible and powerful than the Python class system. - Julia structures may have exactly one abstract supertype, whereas Python classes can inherit from one or more (abstract or concrete) superclasses.
- The logical Julia program structure (Packages and Modules) is independent of the file structure (
include
for additional files), whereas the Python code structure is defined by directories (Packages) and files (Modules). - The ternary operator
x > 0 ? 1 : -1
in Julia corresponds to a conditional expression in Python1 if x > 0 else -1
. - In Julia the
@
symbol refers to a macro, whereas in Python it refers to a decorator. - Exception handling in Julia is done using
try
—catch
—finally
, instead oftry
—except
—finally
. In contrast to Python, it is not recommended to use exception handling as part of the normal workflow in Julia (compared with Python, Julia is faster at ordinary control flow but slower at exception-catching). - In Julia loops are fast, there is no need to write “vectorized” code for performance reasons.
- Be careful with non-constant global variables in Julia, especially in tight loops. Since you can write close-to-metal code in Julia (unlike Python), the effect of globals can be drastic (seePerformance Tips).
- In Julia, rounding and truncation are explicit. Python’s
int(3.7)
should befloor(Int, 3.7)
orInt(floor(3.7))
and is distinguished fromround(Int, 3.7)
.floor(x)
andround(x)
on their own return an integer value of the same type asx
rather than always returningInt
. - In Julia, parsing is explicit. Python’s
float("3.7")
would beparse(Float64, "3.7")
in Julia. - In Python, the majority of values can be used in logical contexts (e.g.
if "a":
means the following block is executed, andif "":
means it is not). In Julia, you need explicit conversion toBool
(e.g.if "a"
throws an exception). If you want to test for a non-empty string in Julia, you would explicitly writeif !isempty("")
. Perhaps surprisingly, in Pythonif "False"
andbool("False")
both evaluate toTrue
(because"False"
is a non-empty string); in Julia,parse(Bool, "false")
returnsfalse
. - In Julia, a new local scope is introduced by most code blocks, including loops and
try
—catch
—finally
. Note that comprehensions (list, generator, etc.) introduce a new local scope both in Python and Julia, whereasif
blocks do not introduce a new local scope in both languages.
Noteworthy differences from Python
How does slicing differ in Julia compared to Python?
Noteworthy differences from Python
- Julia’s
for
,if
,while
, etc. blocks are terminated by theend
keyword. Indentation level is not significant as it is in Python. Unlike Python, Julia has nopass
keyword. - Strings are denoted by double quotation marks (
"text"
) in Julia (with three double quotation marks for multi-line strings), whereas in Python they can be denoted either by single ('text'
) or double quotation marks ("text"
). Single quotation marks are used for characters in Julia ('c'
). - String concatenation is done with
*
in Julia, not+
like in Python. Analogously, string repetition is done with^
, not*
. Implicit string concatenation of string literals like in Python (e.g.'ab' 'cd' == 'abcd'
) is not done in Julia. - Python Lists—flexible but slow—correspond to the Julia
Vector{Any}
type or more generallyVector{T}
whereT
is some non-concrete element type. “Fast” arrays like NumPy arrays that store elements in-place (i.e.,dtype
isnp.float64
,[('f1', np.uint64), ('f2', np.int32)]
, etc.) can be represented byArray{T}
whereT
is a concrete, immutable element type. This includes built-in types likeFloat64
,Int32
,Int64
but also more complex types likeTuple{UInt64,Float64}
and many user-defined types as well. - In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.
- Julia’s slice indexing includes the last element, unlike in Python.
a[2:3]
in Julia isa[1:3]
in Python. - Unlike Python, Julia allowsAbstractArrays with arbitrary indexes. Python’s special interpretation of negative indexing,
a[-1]
anda[-2]
, should be writtena[end]
anda[end-1]
in Julia. - Julia requires
end
for indexing until the last element.x[1:]
in Python is equivalent tox[2:end]
in Julia. - In Julia,
:
before any object creates aSymbol
or_quotes_an expression; so,x[:5]
is same asx[5]
. If you want to get the firstn
elements of an array, then use range indexing. - Julia’s range indexing has the format of
x[start:step:stop]
, whereas Python’s format isx[start:(stop+1):step]
. Hence,x[0:10:2]
in Python is equivalent tox[1:2:10]
in Julia. Similarly,x[::-1]
in Python, which refers to the reversed array, is equivalent tox[end:-1:1]
in Julia. - In Julia, ranges can be constructed independently as
start:step:stop
, the same syntax it uses in array-indexing. Therange
function is also supported. - In Julia, indexing a matrix with arrays like
X[[1,2], [1,3]]
refers to a sub-matrix that contains the intersections of the first and second rows with the first and third columns. In Python,X[[1,2], [1,3]]
refers to a vector that contains the values of cell[1,1]
and[2,3]
in the matrix.X[[1,2], [1,3]]
in Julia is equivalent withX[np.ix_([0,1],[0,2])]
in Python.X[[0,1], [0,2]]
in Python is equivalent withX[[CartesianIndex(1,1), CartesianIndex(2,3)]]
in Julia. - Julia has no line continuation syntax: if, at the end of a line, the input so far is a complete expression, it is considered done; otherwise the input continues. One way to force an expression to continue is to wrap it in parentheses.
- Julia arrays are column-major (Fortran-ordered) whereas NumPy arrays are row-major (C-ordered) by default. To get optimal performance when looping over arrays, the order of the loops should be reversed in Julia relative to NumPy (seerelevant section of Performance Tips).
- Julia’s updating operators (e.g.
+=
,-=
, …) are_not in-place_whereas NumPy’s are. This meansA = [1, 1]; B = A; B += [3, 3]
doesn’t change values inA
, it rather rebinds the nameB
to the result of the right-hand sideB = B + 3
, which is a new array. For in-place operation, useB .+= 3
(see alsodot operators), explicit loops, orInplaceOps.jl
. - Julia evaluates default values of function arguments every time the method is invoked, unlike in Python where the default values are evaluated only once when the function is defined. For example, the function
f(x=rand()) = x
returns a new random number every time it is invoked without argument. On the other hand, the functiong(x=[1,2]) = push!(x,3)
returns[1,2,3]
every time it is called asg()
. - In Julia, keyword arguments must be passed using keywords, unlike Python in which it is usually possible to pass them positionally. Attempting to pass a keyword argument positionally alters the method signature leading to a
MethodError
or calling of the wrong method. - In Julia
%
is the remainder operator, whereas in Python it is the modulus. - In Julia, the commonly used
Int
type corresponds to the machine integer type (Int32
orInt64
), unlike in Python, whereint
is an arbitrary length integer. This means in Julia theInt
type will overflow, such that2^64 == 0
. If you need larger values use another appropriate type, such asInt128
,BigInt
or a floating point type likeFloat64
. - The imaginary unit
sqrt(-1)
is represented in Julia asim
, notj
as in Python. - In Julia, the exponentiation operator is
^
, not**
as in Python. - Julia uses
nothing
of typeNothing
to represent a null value, whereas Python usesNone
of typeNoneType
. - In Julia, the standard operators over a matrix type are matrix operations, whereas, in Python, the standard operators are element-wise operations. When both
A
andB
are matrices,A * B
in Julia performs matrix multiplication, not element-wise multiplication as in Python.A * B
in Julia is equivalent withA @ B
in Python, whereasA * B
in Python is equivalent withA .* B
in Julia. - The adjoint operator
'
in Julia returns an adjoint of a vector (a lazy representation of row vector), whereas the transpose operator.T
over a vector in Python returns the original vector (non-op). - In Julia, a function may contain multiple concrete implementations (called_methods_), which are selected via multiple dispatch based on the types of all arguments to the call, as compared to functions in Python, which have a single implementation and no polymorphism (as opposed to Python method calls which use a different syntax and allows dispatch on the receiver of the method).
- There are no classes in Julia. Instead there are structures (mutable or immutable), containing data but no methods.
- Calling a method of a class instance in Python (
x = MyClass(*args); x.f(y)
) corresponds to a function call in Julia, e.g.x = MyType(args...); f(x, y)
. In general, multiple dispatch is more flexible and powerful than the Python class system. - Julia structures may have exactly one abstract supertype, whereas Python classes can inherit from one or more (abstract or concrete) superclasses.
- The logical Julia program structure (Packages and Modules) is independent of the file structure (
include
for additional files), whereas the Python code structure is defined by directories (Packages) and files (Modules). - The ternary operator
x > 0 ? 1 : -1
in Julia corresponds to a conditional expression in Python1 if x > 0 else -1
. - In Julia the
@
symbol refers to a macro, whereas in Python it refers to a decorator. - Exception handling in Julia is done using
try
—catch
—finally
, instead oftry
—except
—finally
. In contrast to Python, it is not recommended to use exception handling as part of the normal workflow in Julia (compared with Python, Julia is faster at ordinary control flow but slower at exception-catching). - In Julia loops are fast, there is no need to write “vectorized” code for performance reasons.
- Be careful with non-constant global variables in Julia, especially in tight loops. Since you can write close-to-metal code in Julia (unlike Python), the effect of globals can be drastic (seePerformance Tips).
- In Julia, rounding and truncation are explicit. Python’s
int(3.7)
should befloor(Int, 3.7)
orInt(floor(3.7))
and is distinguished fromround(Int, 3.7)
.floor(x)
andround(x)
on their own return an integer value of the same type asx
rather than always returningInt
. - In Julia, parsing is explicit. Python’s
float("3.7")
would beparse(Float64, "3.7")
in Julia. - In Python, the majority of values can be used in logical contexts (e.g.
if "a":
means the following block is executed, andif "":
means it is not). In Julia, you need explicit conversion toBool
(e.g.if "a"
throws an exception). If you want to test for a non-empty string in Julia, you would explicitly writeif !isempty("")
. Perhaps surprisingly, in Pythonif "False"
andbool("False")
both evaluate toTrue
(because"False"
is a non-empty string); in Julia,parse(Bool, "false")
returnsfalse
. - In Julia, a new local scope is introduced by most code blocks, including loops and
try
—catch
—finally
. Note that comprehensions (list, generator, etc.) introduce a new local scope both in Python and Julia, whereasif
blocks do not introduce a new local scope in both languages.
Noteworthy differences from Python
How should Python’s negative indexing, such as a[-1] be written in Julia?
Noteworthy differences from Python
- Julia’s
for
,if
,while
, etc. blocks are terminated by theend
keyword. Indentation level is not significant as it is in Python. Unlike Python, Julia has nopass
keyword. - Strings are denoted by double quotation marks (
"text"
) in Julia (with three double quotation marks for multi-line strings), whereas in Python they can be denoted either by single ('text'
) or double quotation marks ("text"
). Single quotation marks are used for characters in Julia ('c'
). - String concatenation is done with
*
in Julia, not+
like in Python. Analogously, string repetition is done with^
, not*
. Implicit string concatenation of string literals like in Python (e.g.'ab' 'cd' == 'abcd'
) is not done in Julia. - Python Lists—flexible but slow—correspond to the Julia
Vector{Any}
type or more generallyVector{T}
whereT
is some non-concrete element type. “Fast” arrays like NumPy arrays that store elements in-place (i.e.,dtype
isnp.float64
,[('f1', np.uint64), ('f2', np.int32)]
, etc.) can be represented byArray{T}
whereT
is a concrete, immutable element type. This includes built-in types likeFloat64
,Int32
,Int64
but also more complex types likeTuple{UInt64,Float64}
and many user-defined types as well. - In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.
- Julia’s slice indexing includes the last element, unlike in Python.
a[2:3]
in Julia isa[1:3]
in Python. - Unlike Python, Julia allowsAbstractArrays with arbitrary indexes. Python’s special interpretation of negative indexing,
a[-1]
anda[-2]
, should be writtena[end]
anda[end-1]
in Julia. - Julia requires
end
for indexing until the last element.x[1:]
in Python is equivalent tox[2:end]
in Julia. - In Julia,
:
before any object creates aSymbol
or_quotes_an expression; so,x[:5]
is same asx[5]
. If you want to get the firstn
elements of an array, then use range indexing. - Julia’s range indexing has the format of
x[start:step:stop]
, whereas Python’s format isx[start:(stop+1):step]
. Hence,x[0:10:2]
in Python is equivalent tox[1:2:10]
in Julia. Similarly,x[::-1]
in Python, which refers to the reversed array, is equivalent tox[end:-1:1]
in Julia. - In Julia, ranges can be constructed independently as
start:step:stop
, the same syntax it uses in array-indexing. Therange
function is also supported. - In Julia, indexing a matrix with arrays like
X[[1,2], [1,3]]
refers to a sub-matrix that contains the intersections of the first and second rows with the first and third columns. In Python,X[[1,2], [1,3]]
refers to a vector that contains the values of cell[1,1]
and[2,3]
in the matrix.X[[1,2], [1,3]]
in Julia is equivalent withX[np.ix_([0,1],[0,2])]
in Python.X[[0,1], [0,2]]
in Python is equivalent withX[[CartesianIndex(1,1), CartesianIndex(2,3)]]
in Julia. - Julia has no line continuation syntax: if, at the end of a line, the input so far is a complete expression, it is considered done; otherwise the input continues. One way to force an expression to continue is to wrap it in parentheses.
- Julia arrays are column-major (Fortran-ordered) whereas NumPy arrays are row-major (C-ordered) by default. To get optimal performance when looping over arrays, the order of the loops should be reversed in Julia relative to NumPy (seerelevant section of Performance Tips).
- Julia’s updating operators (e.g.
+=
,-=
, …) are_not in-place_whereas NumPy’s are. This meansA = [1, 1]; B = A; B += [3, 3]
doesn’t change values inA
, it rather rebinds the nameB
to the result of the right-hand sideB = B + 3
, which is a new array. For in-place operation, useB .+= 3
(see alsodot operators), explicit loops, orInplaceOps.jl
. - Julia evaluates default values of function arguments every time the method is invoked, unlike in Python where the default values are evaluated only once when the function is defined. For example, the function
f(x=rand()) = x
returns a new random number every time it is invoked without argument. On the other hand, the functiong(x=[1,2]) = push!(x,3)
returns[1,2,3]
every time it is called asg()
. - In Julia, keyword arguments must be passed using keywords, unlike Python in which it is usually possible to pass them positionally. Attempting to pass a keyword argument positionally alters the method signature leading to a
MethodError
or calling of the wrong method. - In Julia
%
is the remainder operator, whereas in Python it is the modulus. - In Julia, the commonly used
Int
type corresponds to the machine integer type (Int32
orInt64
), unlike in Python, whereint
is an arbitrary length integer. This means in Julia theInt
type will overflow, such that2^64 == 0
. If you need larger values use another appropriate type, such asInt128
,BigInt
or a floating point type likeFloat64
. - The imaginary unit
sqrt(-1)
is represented in Julia asim
, notj
as in Python. - In Julia, the exponentiation operator is
^
, not**
as in Python. - Julia uses
nothing
of typeNothing
to represent a null value, whereas Python usesNone
of typeNoneType
. - In Julia, the standard operators over a matrix type are matrix operations, whereas, in Python, the standard operators are element-wise operations. When both
A
andB
are matrices,A * B
in Julia performs matrix multiplication, not element-wise multiplication as in Python.A * B
in Julia is equivalent withA @ B
in Python, whereasA * B
in Python is equivalent withA .* B
in Julia. - The adjoint operator
'
in Julia returns an adjoint of a vector (a lazy representation of row vector), whereas the transpose operator.T
over a vector in Python returns the original vector (non-op). - In Julia, a function may contain multiple concrete implementations (called_methods_), which are selected via multiple dispatch based on the types of all arguments to the call, as compared to functions in Python, which have a single implementation and no polymorphism (as opposed to Python method calls which use a different syntax and allows dispatch on the receiver of the method).
- There are no classes in Julia. Instead there are structures (mutable or immutable), containing data but no methods.
- Calling a method of a class instance in Python (
x = MyClass(*args); x.f(y)
) corresponds to a function call in Julia, e.g.x = MyType(args...); f(x, y)
. In general, multiple dispatch is more flexible and powerful than the Python class system. - Julia structures may have exactly one abstract supertype, whereas Python classes can inherit from one or more (abstract or concrete) superclasses.
- The logical Julia program structure (Packages and Modules) is independent of the file structure (
include
for additional files), whereas the Python code structure is defined by directories (Packages) and files (Modules). - The ternary operator
x > 0 ? 1 : -1
in Julia corresponds to a conditional expression in Python1 if x > 0 else -1
. - In Julia the
@
symbol refers to a macro, whereas in Python it refers to a decorator. - Exception handling in Julia is done using
try
—catch
—finally
, instead oftry
—except
—finally
. In contrast to Python, it is not recommended to use exception handling as part of the normal workflow in Julia (compared with Python, Julia is faster at ordinary control flow but slower at exception-catching). - In Julia loops are fast, there is no need to write “vectorized” code for performance reasons.
- Be careful with non-constant global variables in Julia, especially in tight loops. Since you can write close-to-metal code in Julia (unlike Python), the effect of globals can be drastic (seePerformance Tips).
- In Julia, rounding and truncation are explicit. Python’s
int(3.7)
should befloor(Int, 3.7)
orInt(floor(3.7))
and is distinguished fromround(Int, 3.7)
.floor(x)
andround(x)
on their own return an integer value of the same type asx
rather than always returningInt
. - In Julia, parsing is explicit. Python’s
float("3.7")
would beparse(Float64, "3.7")
in Julia. - In Python, the majority of values can be used in logical contexts (e.g.
if "a":
means the following block is executed, andif "":
means it is not). In Julia, you need explicit conversion toBool
(e.g.if "a"
throws an exception). If you want to test for a non-empty string in Julia, you would explicitly writeif !isempty("")
. Perhaps surprisingly, in Pythonif "False"
andbool("False")
both evaluate toTrue
(because"False"
is a non-empty string); in Julia,parse(Bool, "false")
returnsfalse
. - In Julia, a new local scope is introduced by most code blocks, including loops and
try
—catch
—finally
. Note that comprehensions (list, generator, etc.) introduce a new local scope both in Python and Julia, whereasif
blocks do not introduce a new local scope in both languages.
Noteworthy differences from Python
When indexing, slicing, to the last element, how does Julia differ from Python?
Noteworthy differences from Python
- Julia’s
for
,if
,while
, etc. blocks are terminated by theend
keyword. Indentation level is not significant as it is in Python. Unlike Python, Julia has nopass
keyword. - Strings are denoted by double quotation marks (
"text"
) in Julia (with three double quotation marks for multi-line strings), whereas in Python they can be denoted either by single ('text'
) or double quotation marks ("text"
). Single quotation marks are used for characters in Julia ('c'
). - String concatenation is done with
*
in Julia, not+
like in Python. Analogously, string repetition is done with^
, not*
. Implicit string concatenation of string literals like in Python (e.g.'ab' 'cd' == 'abcd'
) is not done in Julia. - Python Lists—flexible but slow—correspond to the Julia
Vector{Any}
type or more generallyVector{T}
whereT
is some non-concrete element type. “Fast” arrays like NumPy arrays that store elements in-place (i.e.,dtype
isnp.float64
,[('f1', np.uint64), ('f2', np.int32)]
, etc.) can be represented byArray{T}
whereT
is a concrete, immutable element type. This includes built-in types likeFloat64
,Int32
,Int64
but also more complex types likeTuple{UInt64,Float64}
and many user-defined types as well. - In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.
- Julia’s slice indexing includes the last element, unlike in Python.
a[2:3]
in Julia isa[1:3]
in Python. - Unlike Python, Julia allowsAbstractArrays with arbitrary indexes. Python’s special interpretation of negative indexing,
a[-1]
anda[-2]
, should be writtena[end]
anda[end-1]
in Julia. - Julia requires
end
for indexing until the last element.x[1:]
in Python is equivalent tox[2:end]
in Julia. - In Julia,
:
before any object creates aSymbol
or_quotes_an expression; so,x[:5]
is same asx[5]
. If you want to get the firstn
elements of an array, then use range indexing. - Julia’s range indexing has the format of
x[start:step:stop]
, whereas Python’s format isx[start:(stop+1):step]
. Hence,x[0:10:2]
in Python is equivalent tox[1:2:10]
in Julia. Similarly,x[::-1]
in Python, which refers to the reversed array, is equivalent tox[end:-1:1]
in Julia. - In Julia, ranges can be constructed independently as
start:step:stop
, the same syntax it uses in array-indexing. Therange
function is also supported. - In Julia, indexing a matrix with arrays like
X[[1,2], [1,3]]
refers to a sub-matrix that contains the intersections of the first and second rows with the first and third columns. In Python,X[[1,2], [1,3]]
refers to a vector that contains the values of cell[1,1]
and[2,3]
in the matrix.X[[1,2], [1,3]]
in Julia is equivalent withX[np.ix_([0,1],[0,2])]
in Python.X[[0,1], [0,2]]
in Python is equivalent withX[[CartesianIndex(1,1), CartesianIndex(2,3)]]
in Julia. - Julia has no line continuation syntax: if, at the end of a line, the input so far is a complete expression, it is considered done; otherwise the input continues. One way to force an expression to continue is to wrap it in parentheses.
- Julia arrays are column-major (Fortran-ordered) whereas NumPy arrays are row-major (C-ordered) by default. To get optimal performance when looping over arrays, the order of the loops should be reversed in Julia relative to NumPy (seerelevant section of Performance Tips).
- Julia’s updating operators (e.g.
+=
,-=
, …) are_not in-place_whereas NumPy’s are. This meansA = [1, 1]; B = A; B += [3, 3]
doesn’t change values inA
, it rather rebinds the nameB
to the result of the right-hand sideB = B + 3
, which is a new array. For in-place operation, useB .+= 3
(see alsodot operators), explicit loops, orInplaceOps.jl
. - Julia evaluates default values of function arguments every time the method is invoked, unlike in Python where the default values are evaluated only once when the function is defined. For example, the function
f(x=rand()) = x
returns a new random number every time it is invoked without argument. On the other hand, the functiong(x=[1,2]) = push!(x,3)
returns[1,2,3]
every time it is called asg()
. - In Julia, keyword arguments must be passed using keywords, unlike Python in which it is usually possible to pass them positionally. Attempting to pass a keyword argument positionally alters the method signature leading to a
MethodError
or calling of the wrong method. - In Julia
%
is the remainder operator, whereas in Python it is the modulus. - In Julia, the commonly used
Int
type corresponds to the machine integer type (Int32
orInt64
), unlike in Python, whereint
is an arbitrary length integer. This means in Julia theInt
type will overflow, such that2^64 == 0
. If you need larger values use another appropriate type, such asInt128
,BigInt
or a floating point type likeFloat64
. - The imaginary unit
sqrt(-1)
is represented in Julia asim
, notj
as in Python. - In Julia, the exponentiation operator is
^
, not**
as in Python. - Julia uses
nothing
of typeNothing
to represent a null value, whereas Python usesNone
of typeNoneType
. - In Julia, the standard operators over a matrix type are matrix operations, whereas, in Python, the standard operators are element-wise operations. When both
A
andB
are matrices,A * B
in Julia performs matrix multiplication, not element-wise multiplication as in Python.A * B
in Julia is equivalent withA @ B
in Python, whereasA * B
in Python is equivalent withA .* B
in Julia. - The adjoint operator
'
in Julia returns an adjoint of a vector (a lazy representation of row vector), whereas the transpose operator.T
over a vector in Python returns the original vector (non-op). - In Julia, a function may contain multiple concrete implementations (called_methods_), which are selected via multiple dispatch based on the types of all arguments to the call, as compared to functions in Python, which have a single implementation and no polymorphism (as opposed to Python method calls which use a different syntax and allows dispatch on the receiver of the method).
- There are no classes in Julia. Instead there are structures (mutable or immutable), containing data but no methods.
- Calling a method of a class instance in Python (
x = MyClass(*args); x.f(y)
) corresponds to a function call in Julia, e.g.x = MyType(args...); f(x, y)
. In general, multiple dispatch is more flexible and powerful than the Python class system. - Julia structures may have exactly one abstract supertype, whereas Python classes can inherit from one or more (abstract or concrete) superclasses.
- The logical Julia program structure (Packages and Modules) is independent of the file structure (
include
for additional files), whereas the Python code structure is defined by directories (Packages) and files (Modules). - The ternary operator
x > 0 ? 1 : -1
in Julia corresponds to a conditional expression in Python1 if x > 0 else -1
. - In Julia the
@
symbol refers to a macro, whereas in Python it refers to a decorator. - Exception handling in Julia is done using
try
—catch
—finally
, instead oftry
—except
—finally
. In contrast to Python, it is not recommended to use exception handling as part of the normal workflow in Julia (compared with Python, Julia is faster at ordinary control flow but slower at exception-catching). - In Julia loops are fast, there is no need to write “vectorized” code for performance reasons.
- Be careful with non-constant global variables in Julia, especially in tight loops. Since you can write close-to-metal code in Julia (unlike Python), the effect of globals can be drastic (seePerformance Tips).
- In Julia, rounding and truncation are explicit. Python’s
int(3.7)
should befloor(Int, 3.7)
orInt(floor(3.7))
and is distinguished fromround(Int, 3.7)
.floor(x)
andround(x)
on their own return an integer value of the same type asx
rather than always returningInt
. - In Julia, parsing is explicit. Python’s
float("3.7")
would beparse(Float64, "3.7")
in Julia. - In Python, the majority of values can be used in logical contexts (e.g.
if "a":
means the following block is executed, andif "":
means it is not). In Julia, you need explicit conversion toBool
(e.g.if "a"
throws an exception). If you want to test for a non-empty string in Julia, you would explicitly writeif !isempty("")
. Perhaps surprisingly, in Pythonif "False"
andbool("False")
both evaluate toTrue
(because"False"
is a non-empty string); in Julia,parse(Bool, "false")
returnsfalse
. - In Julia, a new local scope is introduced by most code blocks, including loops and
try
—catch
—finally
. Note that comprehensions (list, generator, etc.) introduce a new local scope both in Python and Julia, whereasif
blocks do not introduce a new local scope in both languages.
Noteworthy differences from Python
How is range indexing different in Julia compared to Python?
Noteworthy differences from Python
- Julia’s
for
,if
,while
, etc. blocks are terminated by theend
keyword. Indentation level is not significant as it is in Python. Unlike Python, Julia has nopass
keyword. - Strings are denoted by double quotation marks (
"text"
) in Julia (with three double quotation marks for multi-line strings), whereas in Python they can be denoted either by single ('text'
) or double quotation marks ("text"
). Single quotation marks are used for characters in Julia ('c'
). - String concatenation is done with
*
in Julia, not+
like in Python. Analogously, string repetition is done with^
, not*
. Implicit string concatenation of string literals like in Python (e.g.'ab' 'cd' == 'abcd'
) is not done in Julia. - Python Lists—flexible but slow—correspond to the Julia
Vector{Any}
type or more generallyVector{T}
whereT
is some non-concrete element type. “Fast” arrays like NumPy arrays that store elements in-place (i.e.,dtype
isnp.float64
,[('f1', np.uint64), ('f2', np.int32)]
, etc.) can be represented byArray{T}
whereT
is a concrete, immutable element type. This includes built-in types likeFloat64
,Int32
,Int64
but also more complex types likeTuple{UInt64,Float64}
and many user-defined types as well. - In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.
- Julia’s slice indexing includes the last element, unlike in Python.
a[2:3]
in Julia isa[1:3]
in Python. - Unlike Python, Julia allowsAbstractArrays with arbitrary indexes. Python’s special interpretation of negative indexing,
a[-1]
anda[-2]
, should be writtena[end]
anda[end-1]
in Julia. - Julia requires
end
for indexing until the last element.x[1:]
in Python is equivalent tox[2:end]
in Julia. - In Julia,
:
before any object creates aSymbol
or_quotes_an expression; so,x[:5]
is same asx[5]
. If you want to get the firstn
elements of an array, then use range indexing. - Julia’s range indexing has the format of
x[start:step:stop]
, whereas Python’s format isx[start:(stop+1):step]
. Hence,x[0:10:2]
in Python is equivalent tox[1:2:10]
in Julia. Similarly,x[::-1]
in Python, which refers to the reversed array, is equivalent tox[end:-1:1]
in Julia. - In Julia, ranges can be constructed independently as
start:step:stop
, the same syntax it uses in array-indexing. Therange
function is also supported. - In Julia, indexing a matrix with arrays like
X[[1,2], [1,3]]
refers to a sub-matrix that contains the intersections of the first and second rows with the first and third columns. In Python,X[[1,2], [1,3]]
refers to a vector that contains the values of cell[1,1]
and[2,3]
in the matrix.X[[1,2], [1,3]]
in Julia is equivalent withX[np.ix_([0,1],[0,2])]
in Python.X[[0,1], [0,2]]
in Python is equivalent withX[[CartesianIndex(1,1), CartesianIndex(2,3)]]
in Julia. - Julia has no line continuation syntax: if, at the end of a line, the input so far is a complete expression, it is considered done; otherwise the input continues. One way to force an expression to continue is to wrap it in parentheses.
- Julia arrays are column-major (Fortran-ordered) whereas NumPy arrays are row-major (C-ordered) by default. To get optimal performance when looping over arrays, the order of the loops should be reversed in Julia relative to NumPy (seerelevant section of Performance Tips).
- Julia’s updating operators (e.g.
+=
,-=
, …) are_not in-place_whereas NumPy’s are. This meansA = [1, 1]; B = A; B += [3, 3]
doesn’t change values inA
, it rather rebinds the nameB
to the result of the right-hand sideB = B + 3
, which is a new array. For in-place operation, useB .+= 3
(see alsodot operators), explicit loops, orInplaceOps.jl
. - Julia evaluates default values of function arguments every time the method is invoked, unlike in Python where the default values are evaluated only once when the function is defined. For example, the function
f(x=rand()) = x
returns a new random number every time it is invoked without argument. On the other hand, the functiong(x=[1,2]) = push!(x,3)
returns[1,2,3]
every time it is called asg()
. - In Julia, keyword arguments must be passed using keywords, unlike Python in which it is usually possible to pass them positionally. Attempting to pass a keyword argument positionally alters the method signature leading to a
MethodError
or calling of the wrong method. - In Julia
%
is the remainder operator, whereas in Python it is the modulus. - In Julia, the commonly used
Int
type corresponds to the machine integer type (Int32
orInt64
), unlike in Python, whereint
is an arbitrary length integer. This means in Julia theInt
type will overflow, such that2^64 == 0
. If you need larger values use another appropriate type, such asInt128
,BigInt
or a floating point type likeFloat64
. - The imaginary unit
sqrt(-1)
is represented in Julia asim
, notj
as in Python. - In Julia, the exponentiation operator is
^
, not**
as in Python. - Julia uses
nothing
of typeNothing
to represent a null value, whereas Python usesNone
of typeNoneType
. - In Julia, the standard operators over a matrix type are matrix operations, whereas, in Python, the standard operators are element-wise operations. When both
A
andB
are matrices,A * B
in Julia performs matrix multiplication, not element-wise multiplication as in Python.A * B
in Julia is equivalent withA @ B
in Python, whereasA * B
in Python is equivalent withA .* B
in Julia. - The adjoint operator
'
in Julia returns an adjoint of a vector (a lazy representation of row vector), whereas the transpose operator.T
over a vector in Python returns the original vector (non-op). - In Julia, a function may contain multiple concrete implementations (called_methods_), which are selected via multiple dispatch based on the types of all arguments to the call, as compared to functions in Python, which have a single implementation and no polymorphism (as opposed to Python method calls which use a different syntax and allows dispatch on the receiver of the method).
- There are no classes in Julia. Instead there are structures (mutable or immutable), containing data but no methods.
- Calling a method of a class instance in Python (
x = MyClass(*args); x.f(y)
) corresponds to a function call in Julia, e.g.x = MyType(args...); f(x, y)
. In general, multiple dispatch is more flexible and powerful than the Python class system. - Julia structures may have exactly one abstract supertype, whereas Python classes can inherit from one or more (abstract or concrete) superclasses.
- The logical Julia program structure (Packages and Modules) is independent of the file structure (
include
for additional files), whereas the Python code structure is defined by directories (Packages) and files (Modules). - The ternary operator
x > 0 ? 1 : -1
in Julia corresponds to a conditional expression in Python1 if x > 0 else -1
. - In Julia the
@
symbol refers to a macro, whereas in Python it refers to a decorator. - Exception handling in Julia is done using
try
—catch
—finally
, instead oftry
—except
—finally
. In contrast to Python, it is not recommended to use exception handling as part of the normal workflow in Julia (compared with Python, Julia is faster at ordinary control flow but slower at exception-catching). - In Julia loops are fast, there is no need to write “vectorized” code for performance reasons.
- Be careful with non-constant global variables in Julia, especially in tight loops. Since you can write close-to-metal code in Julia (unlike Python), the effect of globals can be drastic (seePerformance Tips).
- In Julia, rounding and truncation are explicit. Python’s
int(3.7)
should befloor(Int, 3.7)
orInt(floor(3.7))
and is distinguished fromround(Int, 3.7)
.floor(x)
andround(x)
on their own return an integer value of the same type asx
rather than always returningInt
. - In Julia, parsing is explicit. Python’s
float("3.7")
would beparse(Float64, "3.7")
in Julia. - In Python, the majority of values can be used in logical contexts (e.g.
if "a":
means the following block is executed, andif "":
means it is not). In Julia, you need explicit conversion toBool
(e.g.if "a"
throws an exception). If you want to test for a non-empty string in Julia, you would explicitly writeif !isempty("")
. Perhaps surprisingly, in Pythonif "False"
andbool("False")
both evaluate toTrue
(because"False"
is a non-empty string); in Julia,parse(Bool, "false")
returnsfalse
. - In Julia, a new local scope is introduced by most code blocks, including loops and
try
—catch
—finally
. Note that comprehensions (list, generator, etc.) introduce a new local scope both in Python and Julia, whereasif
blocks do not introduce a new local scope in both languages.
Noteworthy differences from Python
How does Julia’s line continuation syntax differ from Python’s?
Noteworthy differences from Python
- Julia’s
for
,if
,while
, etc. blocks are terminated by theend
keyword. Indentation level is not significant as it is in Python. Unlike Python, Julia has nopass
keyword. - Strings are denoted by double quotation marks (
"text"
) in Julia (with three double quotation marks for multi-line strings), whereas in Python they can be denoted either by single ('text'
) or double quotation marks ("text"
). Single quotation marks are used for characters in Julia ('c'
). - String concatenation is done with
*
in Julia, not+
like in Python. Analogously, string repetition is done with^
, not*
. Implicit string concatenation of string literals like in Python (e.g.'ab' 'cd' == 'abcd'
) is not done in Julia. - Python Lists—flexible but slow—correspond to the Julia
Vector{Any}
type or more generallyVector{T}
whereT
is some non-concrete element type. “Fast” arrays like NumPy arrays that store elements in-place (i.e.,dtype
isnp.float64
,[('f1', np.uint64), ('f2', np.int32)]
, etc.) can be represented byArray{T}
whereT
is a concrete, immutable element type. This includes built-in types likeFloat64
,Int32
,Int64
but also more complex types likeTuple{UInt64,Float64}
and many user-defined types as well. - In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.
- Julia’s slice indexing includes the last element, unlike in Python.
a[2:3]
in Julia isa[1:3]
in Python. - Unlike Python, Julia allowsAbstractArrays with arbitrary indexes. Python’s special interpretation of negative indexing,
a[-1]
anda[-2]
, should be writtena[end]
anda[end-1]
in Julia. - Julia requires
end
for indexing until the last element.x[1:]
in Python is equivalent tox[2:end]
in Julia. - In Julia,
:
before any object creates aSymbol
or_quotes_an expression; so,x[:5]
is same asx[5]
. If you want to get the firstn
elements of an array, then use range indexing. - Julia’s range indexing has the format of
x[start:step:stop]
, whereas Python’s format isx[start:(stop+1):step]
. Hence,x[0:10:2]
in Python is equivalent tox[1:2:10]
in Julia. Similarly,x[::-1]
in Python, which refers to the reversed array, is equivalent tox[end:-1:1]
in Julia. - In Julia, ranges can be constructed independently as
start:step:stop
, the same syntax it uses in array-indexing. Therange
function is also supported. - In Julia, indexing a matrix with arrays like
X[[1,2], [1,3]]
refers to a sub-matrix that contains the intersections of the first and second rows with the first and third columns. In Python,X[[1,2], [1,3]]
refers to a vector that contains the values of cell[1,1]
and[2,3]
in the matrix.X[[1,2], [1,3]]
in Julia is equivalent withX[np.ix_([0,1],[0,2])]
in Python.X[[0,1], [0,2]]
in Python is equivalent withX[[CartesianIndex(1,1), CartesianIndex(2,3)]]
in Julia. - Julia has no line continuation syntax: if, at the end of a line, the input so far is a complete expression, it is considered done; otherwise the input continues. One way to force an expression to continue is to wrap it in parentheses.
- Julia arrays are column-major (Fortran-ordered) whereas NumPy arrays are row-major (C-ordered) by default. To get optimal performance when looping over arrays, the order of the loops should be reversed in Julia relative to NumPy (seerelevant section of Performance Tips).
- Julia’s updating operators (e.g.
+=
,-=
, …) are_not in-place_whereas NumPy’s are. This meansA = [1, 1]; B = A; B += [3, 3]
doesn’t change values inA
, it rather rebinds the nameB
to the result of the right-hand sideB = B + 3
, which is a new array. For in-place operation, useB .+= 3
(see alsodot operators), explicit loops, orInplaceOps.jl
. - Julia evaluates default values of function arguments every time the method is invoked, unlike in Python where the default values are evaluated only once when the function is defined. For example, the function
f(x=rand()) = x
returns a new random number every time it is invoked without argument. On the other hand, the functiong(x=[1,2]) = push!(x,3)
returns[1,2,3]
every time it is called asg()
. - In Julia, keyword arguments must be passed using keywords, unlike Python in which it is usually possible to pass them positionally. Attempting to pass a keyword argument positionally alters the method signature leading to a
MethodError
or calling of the wrong method. - In Julia
%
is the remainder operator, whereas in Python it is the modulus. - In Julia, the commonly used
Int
type corresponds to the machine integer type (Int32
orInt64
), unlike in Python, whereint
is an arbitrary length integer. This means in Julia theInt
type will overflow, such that2^64 == 0
. If you need larger values use another appropriate type, such asInt128
,BigInt
or a floating point type likeFloat64
. - The imaginary unit
sqrt(-1)
is represented in Julia asim
, notj
as in Python. - In Julia, the exponentiation operator is
^
, not**
as in Python. - Julia uses
nothing
of typeNothing
to represent a null value, whereas Python usesNone
of typeNoneType
. - In Julia, the standard operators over a matrix type are matrix operations, whereas, in Python, the standard operators are element-wise operations. When both
A
andB
are matrices,A * B
in Julia performs matrix multiplication, not element-wise multiplication as in Python.A * B
in Julia is equivalent withA @ B
in Python, whereasA * B
in Python is equivalent withA .* B
in Julia. - The adjoint operator
'
in Julia returns an adjoint of a vector (a lazy representation of row vector), whereas the transpose operator.T
over a vector in Python returns the original vector (non-op). - In Julia, a function may contain multiple concrete implementations (called_methods_), which are selected via multiple dispatch based on the types of all arguments to the call, as compared to functions in Python, which have a single implementation and no polymorphism (as opposed to Python method calls which use a different syntax and allows dispatch on the receiver of the method).
- There are no classes in Julia. Instead there are structures (mutable or immutable), containing data but no methods.
- Calling a method of a class instance in Python (
x = MyClass(*args); x.f(y)
) corresponds to a function call in Julia, e.g.x = MyType(args...); f(x, y)
. In general, multiple dispatch is more flexible and powerful than the Python class system. - Julia structures may have exactly one abstract supertype, whereas Python classes can inherit from one or more (abstract or concrete) superclasses.
- The logical Julia program structure (Packages and Modules) is independent of the file structure (
include
for additional files), whereas the Python code structure is defined by directories (Packages) and files (Modules). - The ternary operator
x > 0 ? 1 : -1
in Julia corresponds to a conditional expression in Python1 if x > 0 else -1
. - In Julia the
@
symbol refers to a macro, whereas in Python it refers to a decorator. - Exception handling in Julia is done using
try
—catch
—finally
, instead oftry
—except
—finally
. In contrast to Python, it is not recommended to use exception handling as part of the normal workflow in Julia (compared with Python, Julia is faster at ordinary control flow but slower at exception-catching). - In Julia loops are fast, there is no need to write “vectorized” code for performance reasons.
- Be careful with non-constant global variables in Julia, especially in tight loops. Since you can write close-to-metal code in Julia (unlike Python), the effect of globals can be drastic (seePerformance Tips).
- In Julia, rounding and truncation are explicit. Python’s
int(3.7)
should befloor(Int, 3.7)
orInt(floor(3.7))
and is distinguished fromround(Int, 3.7)
.floor(x)
andround(x)
on their own return an integer value of the same type asx
rather than always returningInt
. - In Julia, parsing is explicit. Python’s
float("3.7")
would beparse(Float64, "3.7")
in Julia. - In Python, the majority of values can be used in logical contexts (e.g.
if "a":
means the following block is executed, andif "":
means it is not). In Julia, you need explicit conversion toBool
(e.g.if "a"
throws an exception). If you want to test for a non-empty string in Julia, you would explicitly writeif !isempty("")
. Perhaps surprisingly, in Pythonif "False"
andbool("False")
both evaluate toTrue
(because"False"
is a non-empty string); in Julia,parse(Bool, "false")
returnsfalse
. - In Julia, a new local scope is introduced by most code blocks, including loops and
try
—catch
—finally
. Note that comprehensions (list, generator, etc.) introduce a new local scope both in Python and Julia, whereasif
blocks do not introduce a new local scope in both languages.
Noteworthy differences from Python
How does Julia’s evaluation of default values of function arguments differ from Python’s?
Noteworthy differences from Python
- Julia’s
for
,if
,while
, etc. blocks are terminated by theend
keyword. Indentation level is not significant as it is in Python. Unlike Python, Julia has nopass
keyword. - Strings are denoted by double quotation marks (
"text"
) in Julia (with three double quotation marks for multi-line strings), whereas in Python they can be denoted either by single ('text'
) or double quotation marks ("text"
). Single quotation marks are used for characters in Julia ('c'
). - String concatenation is done with
*
in Julia, not+
like in Python. Analogously, string repetition is done with^
, not*
. Implicit string concatenation of string literals like in Python (e.g.'ab' 'cd' == 'abcd'
) is not done in Julia. - Python Lists—flexible but slow—correspond to the Julia
Vector{Any}
type or more generallyVector{T}
whereT
is some non-concrete element type. “Fast” arrays like NumPy arrays that store elements in-place (i.e.,dtype
isnp.float64
,[('f1', np.uint64), ('f2', np.int32)]
, etc.) can be represented byArray{T}
whereT
is a concrete, immutable element type. This includes built-in types likeFloat64
,Int32
,Int64
but also more complex types likeTuple{UInt64,Float64}
and many user-defined types as well. - In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.
- Julia’s slice indexing includes the last element, unlike in Python.
a[2:3]
in Julia isa[1:3]
in Python. - Unlike Python, Julia allowsAbstractArrays with arbitrary indexes. Python’s special interpretation of negative indexing,
a[-1]
anda[-2]
, should be writtena[end]
anda[end-1]
in Julia. - Julia requires
end
for indexing until the last element.x[1:]
in Python is equivalent tox[2:end]
in Julia. - In Julia,
:
before any object creates aSymbol
or_quotes_an expression; so,x[:5]
is same asx[5]
. If you want to get the firstn
elements of an array, then use range indexing. - Julia’s range indexing has the format of
x[start:step:stop]
, whereas Python’s format isx[start:(stop+1):step]
. Hence,x[0:10:2]
in Python is equivalent tox[1:2:10]
in Julia. Similarly,x[::-1]
in Python, which refers to the reversed array, is equivalent tox[end:-1:1]
in Julia. - In Julia, ranges can be constructed independently as
start:step:stop
, the same syntax it uses in array-indexing. Therange
function is also supported. - In Julia, indexing a matrix with arrays like
X[[1,2], [1,3]]
refers to a sub-matrix that contains the intersections of the first and second rows with the first and third columns. In Python,X[[1,2], [1,3]]
refers to a vector that contains the values of cell[1,1]
and[2,3]
in the matrix.X[[1,2], [1,3]]
in Julia is equivalent withX[np.ix_([0,1],[0,2])]
in Python.X[[0,1], [0,2]]
in Python is equivalent withX[[CartesianIndex(1,1), CartesianIndex(2,3)]]
in Julia. - Julia has no line continuation syntax: if, at the end of a line, the input so far is a complete expression, it is considered done; otherwise the input continues. One way to force an expression to continue is to wrap it in parentheses.
- Julia arrays are column-major (Fortran-ordered) whereas NumPy arrays are row-major (C-ordered) by default. To get optimal performance when looping over arrays, the order of the loops should be reversed in Julia relative to NumPy (seerelevant section of Performance Tips).
- Julia’s updating operators (e.g.
+=
,-=
, …) are_not in-place_whereas NumPy’s are. This meansA = [1, 1]; B = A; B += [3, 3]
doesn’t change values inA
, it rather rebinds the nameB
to the result of the right-hand sideB = B + 3
, which is a new array. For in-place operation, useB .+= 3
(see alsodot operators), explicit loops, orInplaceOps.jl
. - Julia evaluates default values of function arguments every time the method is invoked, unlike in Python where the default values are evaluated only once when the function is defined. For example, the function
f(x=rand()) = x
returns a new random number every time it is invoked without argument. On the other hand, the functiong(x=[1,2]) = push!(x,3)
returns[1,2,3]
every time it is called asg()
. - In Julia, keyword arguments must be passed using keywords, unlike Python in which it is usually possible to pass them positionally. Attempting to pass a keyword argument positionally alters the method signature leading to a
MethodError
or calling of the wrong method. - In Julia
%
is the remainder operator, whereas in Python it is the modulus. - In Julia, the commonly used
Int
type corresponds to the machine integer type (Int32
orInt64
), unlike in Python, whereint
is an arbitrary length integer. This means in Julia theInt
type will overflow, such that2^64 == 0
. If you need larger values use another appropriate type, such asInt128
,BigInt
or a floating point type likeFloat64
. - The imaginary unit
sqrt(-1)
is represented in Julia asim
, notj
as in Python. - In Julia, the exponentiation operator is
^
, not**
as in Python. - Julia uses
nothing
of typeNothing
to represent a null value, whereas Python usesNone
of typeNoneType
. - In Julia, the standard operators over a matrix type are matrix operations, whereas, in Python, the standard operators are element-wise operations. When both
A
andB
are matrices,A * B
in Julia performs matrix multiplication, not element-wise multiplication as in Python.A * B
in Julia is equivalent withA @ B
in Python, whereasA * B
in Python is equivalent withA .* B
in Julia. - The adjoint operator
'
in Julia returns an adjoint of a vector (a lazy representation of row vector), whereas the transpose operator.T
over a vector in Python returns the original vector (non-op). - In Julia, a function may contain multiple concrete implementations (called_methods_), which are selected via multiple dispatch based on the types of all arguments to the call, as compared to functions in Python, which have a single implementation and no polymorphism (as opposed to Python method calls which use a different syntax and allows dispatch on the receiver of the method).
- There are no classes in Julia. Instead there are structures (mutable or immutable), containing data but no methods.
- Calling a method of a class instance in Python (
x = MyClass(*args); x.f(y)
) corresponds to a function call in Julia, e.g.x = MyType(args...); f(x, y)
. In general, multiple dispatch is more flexible and powerful than the Python class system. - Julia structures may have exactly one abstract supertype, whereas Python classes can inherit from one or more (abstract or concrete) superclasses.
- The logical Julia program structure (Packages and Modules) is independent of the file structure (
include
for additional files), whereas the Python code structure is defined by directories (Packages) and files (Modules). - The ternary operator
x > 0 ? 1 : -1
in Julia corresponds to a conditional expression in Python1 if x > 0 else -1
. - In Julia the
@
symbol refers to a macro, whereas in Python it refers to a decorator. - Exception handling in Julia is done using
try
—catch
—finally
, instead oftry
—except
—finally
. In contrast to Python, it is not recommended to use exception handling as part of the normal workflow in Julia (compared with Python, Julia is faster at ordinary control flow but slower at exception-catching). - In Julia loops are fast, there is no need to write “vectorized” code for performance reasons.
- Be careful with non-constant global variables in Julia, especially in tight loops. Since you can write close-to-metal code in Julia (unlike Python), the effect of globals can be drastic (seePerformance Tips).
- In Julia, rounding and truncation are explicit. Python’s
int(3.7)
should befloor(Int, 3.7)
orInt(floor(3.7))
and is distinguished fromround(Int, 3.7)
.floor(x)
andround(x)
on their own return an integer value of the same type asx
rather than always returningInt
. - In Julia, parsing is explicit. Python’s
float("3.7")
would beparse(Float64, "3.7")
in Julia. - In Python, the majority of values can be used in logical contexts (e.g.
if "a":
means the following block is executed, andif "":
means it is not). In Julia, you need explicit conversion toBool
(e.g.if "a"
throws an exception). If you want to test for a non-empty string in Julia, you would explicitly writeif !isempty("")
. Perhaps surprisingly, in Pythonif "False"
andbool("False")
both evaluate toTrue
(because"False"
is a non-empty string); in Julia,parse(Bool, "false")
returnsfalse
. - In Julia, a new local scope is introduced by most code blocks, including loops and
try
—catch
—finally
. Note that comprehensions (list, generator, etc.) introduce a new local scope both in Python and Julia, whereasif
blocks do not introduce a new local scope in both languages.
Noteworthy differences from Python
How does Julia’s use of keyword arguments differ from Python’s?
Noteworthy differences from Python
- Julia’s
for
,if
,while
, etc. blocks are terminated by theend
keyword. Indentation level is not significant as it is in Python. Unlike Python, Julia has nopass
keyword. - Strings are denoted by double quotation marks (
"text"
) in Julia (with three double quotation marks for multi-line strings), whereas in Python they can be denoted either by single ('text'
) or double quotation marks ("text"
). Single quotation marks are used for characters in Julia ('c'
). - String concatenation is done with
*
in Julia, not+
like in Python. Analogously, string repetition is done with^
, not*
. Implicit string concatenation of string literals like in Python (e.g.'ab' 'cd' == 'abcd'
) is not done in Julia. - Python Lists—flexible but slow—correspond to the Julia
Vector{Any}
type or more generallyVector{T}
whereT
is some non-concrete element type. “Fast” arrays like NumPy arrays that store elements in-place (i.e.,dtype
isnp.float64
,[('f1', np.uint64), ('f2', np.int32)]
, etc.) can be represented byArray{T}
whereT
is a concrete, immutable element type. This includes built-in types likeFloat64
,Int32
,Int64
but also more complex types likeTuple{UInt64,Float64}
and many user-defined types as well. - In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.
- Julia’s slice indexing includes the last element, unlike in Python.
a[2:3]
in Julia isa[1:3]
in Python. - Unlike Python, Julia allowsAbstractArrays with arbitrary indexes. Python’s special interpretation of negative indexing,
a[-1]
anda[-2]
, should be writtena[end]
anda[end-1]
in Julia. - Julia requires
end
for indexing until the last element.x[1:]
in Python is equivalent tox[2:end]
in Julia. - In Julia,
:
before any object creates aSymbol
or_quotes_an expression; so,x[:5]
is same asx[5]
. If you want to get the firstn
elements of an array, then use range indexing. - Julia’s range indexing has the format of
x[start:step:stop]
, whereas Python’s format isx[start:(stop+1):step]
. Hence,x[0:10:2]
in Python is equivalent tox[1:2:10]
in Julia. Similarly,x[::-1]
in Python, which refers to the reversed array, is equivalent tox[end:-1:1]
in Julia. - In Julia, ranges can be constructed independently as
start:step:stop
, the same syntax it uses in array-indexing. Therange
function is also supported. - In Julia, indexing a matrix with arrays like
X[[1,2], [1,3]]
refers to a sub-matrix that contains the intersections of the first and second rows with the first and third columns. In Python,X[[1,2], [1,3]]
refers to a vector that contains the values of cell[1,1]
and[2,3]
in the matrix.X[[1,2], [1,3]]
in Julia is equivalent withX[np.ix_([0,1],[0,2])]
in Python.X[[0,1], [0,2]]
in Python is equivalent withX[[CartesianIndex(1,1), CartesianIndex(2,3)]]
in Julia. - Julia has no line continuation syntax: if, at the end of a line, the input so far is a complete expression, it is considered done; otherwise the input continues. One way to force an expression to continue is to wrap it in parentheses.
- Julia arrays are column-major (Fortran-ordered) whereas NumPy arrays are row-major (C-ordered) by default. To get optimal performance when looping over arrays, the order of the loops should be reversed in Julia relative to NumPy (seerelevant section of Performance Tips).
- Julia’s updating operators (e.g.
+=
,-=
, …) are_not in-place_whereas NumPy’s are. This meansA = [1, 1]; B = A; B += [3, 3]
doesn’t change values inA
, it rather rebinds the nameB
to the result of the right-hand sideB = B + 3
, which is a new array. For in-place operation, useB .+= 3
(see alsodot operators), explicit loops, orInplaceOps.jl
. - Julia evaluates default values of function arguments every time the method is invoked, unlike in Python where the default values are evaluated only once when the function is defined. For example, the function
f(x=rand()) = x
returns a new random number every time it is invoked without argument. On the other hand, the functiong(x=[1,2]) = push!(x,3)
returns[1,2,3]
every time it is called asg()
. - In Julia, keyword arguments must be passed using keywords, unlike Python in which it is usually possible to pass them positionally. Attempting to pass a keyword argument positionally alters the method signature leading to a
MethodError
or calling of the wrong method. - In Julia
%
is the remainder operator, whereas in Python it is the modulus. - In Julia, the commonly used
Int
type corresponds to the machine integer type (Int32
orInt64
), unlike in Python, whereint
is an arbitrary length integer. This means in Julia theInt
type will overflow, such that2^64 == 0
. If you need larger values use another appropriate type, such asInt128
,BigInt
or a floating point type likeFloat64
. - The imaginary unit
sqrt(-1)
is represented in Julia asim
, notj
as in Python. - In Julia, the exponentiation operator is
^
, not**
as in Python. - Julia uses
nothing
of typeNothing
to represent a null value, whereas Python usesNone
of typeNoneType
. - In Julia, the standard operators over a matrix type are matrix operations, whereas, in Python, the standard operators are element-wise operations. When both
A
andB
are matrices,A * B
in Julia performs matrix multiplication, not element-wise multiplication as in Python.A * B
in Julia is equivalent withA @ B
in Python, whereasA * B
in Python is equivalent withA .* B
in Julia. - The adjoint operator
'
in Julia returns an adjoint of a vector (a lazy representation of row vector), whereas the transpose operator.T
over a vector in Python returns the original vector (non-op). - In Julia, a function may contain multiple concrete implementations (called_methods_), which are selected via multiple dispatch based on the types of all arguments to the call, as compared to functions in Python, which have a single implementation and no polymorphism (as opposed to Python method calls which use a different syntax and allows dispatch on the receiver of the method).
- There are no classes in Julia. Instead there are structures (mutable or immutable), containing data but no methods.
- Calling a method of a class instance in Python (
x = MyClass(*args); x.f(y)
) corresponds to a function call in Julia, e.g.x = MyType(args...); f(x, y)
. In general, multiple dispatch is more flexible and powerful than the Python class system. - Julia structures may have exactly one abstract supertype, whereas Python classes can inherit from one or more (abstract or concrete) superclasses.
- The logical Julia program structure (Packages and Modules) is independent of the file structure (
include
for additional files), whereas the Python code structure is defined by directories (Packages) and files (Modules). - The ternary operator
x > 0 ? 1 : -1
in Julia corresponds to a conditional expression in Python1 if x > 0 else -1
. - In Julia the
@
symbol refers to a macro, whereas in Python it refers to a decorator. - Exception handling in Julia is done using
try
—catch
—finally
, instead oftry
—except
—finally
. In contrast to Python, it is not recommended to use exception handling as part of the normal workflow in Julia (compared with Python, Julia is faster at ordinary control flow but slower at exception-catching). - In Julia loops are fast, there is no need to write “vectorized” code for performance reasons.
- Be careful with non-constant global variables in Julia, especially in tight loops. Since you can write close-to-metal code in Julia (unlike Python), the effect of globals can be drastic (seePerformance Tips).
- In Julia, rounding and truncation are explicit. Python’s
int(3.7)
should befloor(Int, 3.7)
orInt(floor(3.7))
and is distinguished fromround(Int, 3.7)
.floor(x)
andround(x)
on their own return an integer value of the same type asx
rather than always returningInt
. - In Julia, parsing is explicit. Python’s
float("3.7")
would beparse(Float64, "3.7")
in Julia. - In Python, the majority of values can be used in logical contexts (e.g.
if "a":
means the following block is executed, andif "":
means it is not). In Julia, you need explicit conversion toBool
(e.g.if "a"
throws an exception). If you want to test for a non-empty string in Julia, you would explicitly writeif !isempty("")
. Perhaps surprisingly, in Pythonif "False"
andbool("False")
both evaluate toTrue
(because"False"
is a non-empty string); in Julia,parse(Bool, "false")
returnsfalse
. - In Julia, a new local scope is introduced by most code blocks, including loops and
try
—catch
—finally
. Note that comprehensions (list, generator, etc.) introduce a new local scope both in Python and Julia, whereasif
blocks do not introduce a new local scope in both languages.
Noteworthy differences from Python
How does Julia represent the imaginary unit, sqrt(-1), compared to Python?
Noteworthy differences from Python
- Julia’s
for
,if
,while
, etc. blocks are terminated by theend
keyword. Indentation level is not significant as it is in Python. Unlike Python, Julia has nopass
keyword. - Strings are denoted by double quotation marks (
"text"
) in Julia (with three double quotation marks for multi-line strings), whereas in Python they can be denoted either by single ('text'
) or double quotation marks ("text"
). Single quotation marks are used for characters in Julia ('c'
). - String concatenation is done with
*
in Julia, not+
like in Python. Analogously, string repetition is done with^
, not*
. Implicit string concatenation of string literals like in Python (e.g.'ab' 'cd' == 'abcd'
) is not done in Julia. - Python Lists—flexible but slow—correspond to the Julia
Vector{Any}
type or more generallyVector{T}
whereT
is some non-concrete element type. “Fast” arrays like NumPy arrays that store elements in-place (i.e.,dtype
isnp.float64
,[('f1', np.uint64), ('f2', np.int32)]
, etc.) can be represented byArray{T}
whereT
is a concrete, immutable element type. This includes built-in types likeFloat64
,Int32
,Int64
but also more complex types likeTuple{UInt64,Float64}
and many user-defined types as well. - In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.
- Julia’s slice indexing includes the last element, unlike in Python.
a[2:3]
in Julia isa[1:3]
in Python. - Unlike Python, Julia allowsAbstractArrays with arbitrary indexes. Python’s special interpretation of negative indexing,
a[-1]
anda[-2]
, should be writtena[end]
anda[end-1]
in Julia. - Julia requires
end
for indexing until the last element.x[1:]
in Python is equivalent tox[2:end]
in Julia. - In Julia,
:
before any object creates aSymbol
or_quotes_an expression; so,x[:5]
is same asx[5]
. If you want to get the firstn
elements of an array, then use range indexing. - Julia’s range indexing has the format of
x[start:step:stop]
, whereas Python’s format isx[start:(stop+1):step]
. Hence,x[0:10:2]
in Python is equivalent tox[1:2:10]
in Julia. Similarly,x[::-1]
in Python, which refers to the reversed array, is equivalent tox[end:-1:1]
in Julia. - In Julia, ranges can be constructed independently as
start:step:stop
, the same syntax it uses in array-indexing. Therange
function is also supported. - In Julia, indexing a matrix with arrays like
X[[1,2], [1,3]]
refers to a sub-matrix that contains the intersections of the first and second rows with the first and third columns. In Python,X[[1,2], [1,3]]
refers to a vector that contains the values of cell[1,1]
and[2,3]
in the matrix.X[[1,2], [1,3]]
in Julia is equivalent withX[np.ix_([0,1],[0,2])]
in Python.X[[0,1], [0,2]]
in Python is equivalent withX[[CartesianIndex(1,1), CartesianIndex(2,3)]]
in Julia. - Julia has no line continuation syntax: if, at the end of a line, the input so far is a complete expression, it is considered done; otherwise the input continues. One way to force an expression to continue is to wrap it in parentheses.
- Julia arrays are column-major (Fortran-ordered) whereas NumPy arrays are row-major (C-ordered) by default. To get optimal performance when looping over arrays, the order of the loops should be reversed in Julia relative to NumPy (seerelevant section of Performance Tips).
- Julia’s updating operators (e.g.
+=
,-=
, …) are_not in-place_whereas NumPy’s are. This meansA = [1, 1]; B = A; B += [3, 3]
doesn’t change values inA
, it rather rebinds the nameB
to the result of the right-hand sideB = B + 3
, which is a new array. For in-place operation, useB .+= 3
(see alsodot operators), explicit loops, orInplaceOps.jl
. - Julia evaluates default values of function arguments every time the method is invoked, unlike in Python where the default values are evaluated only once when the function is defined. For example, the function
f(x=rand()) = x
returns a new random number every time it is invoked without argument. On the other hand, the functiong(x=[1,2]) = push!(x,3)
returns[1,2,3]
every time it is called asg()
. - In Julia, keyword arguments must be passed using keywords, unlike Python in which it is usually possible to pass them positionally. Attempting to pass a keyword argument positionally alters the method signature leading to a
MethodError
or calling of the wrong method. - In Julia
%
is the remainder operator, whereas in Python it is the modulus. - In Julia, the commonly used
Int
type corresponds to the machine integer type (Int32
orInt64
), unlike in Python, whereint
is an arbitrary length integer. This means in Julia theInt
type will overflow, such that2^64 == 0
. If you need larger values use another appropriate type, such asInt128
,BigInt
or a floating point type likeFloat64
. - The imaginary unit
sqrt(-1)
is represented in Julia asim
, notj
as in Python. - In Julia, the exponentiation operator is
^
, not**
as in Python. - Julia uses
nothing
of typeNothing
to represent a null value, whereas Python usesNone
of typeNoneType
. - In Julia, the standard operators over a matrix type are matrix operations, whereas, in Python, the standard operators are element-wise operations. When both
A
andB
are matrices,A * B
in Julia performs matrix multiplication, not element-wise multiplication as in Python.A * B
in Julia is equivalent withA @ B
in Python, whereasA * B
in Python is equivalent withA .* B
in Julia. - The adjoint operator
'
in Julia returns an adjoint of a vector (a lazy representation of row vector), whereas the transpose operator.T
over a vector in Python returns the original vector (non-op). - In Julia, a function may contain multiple concrete implementations (called_methods_), which are selected via multiple dispatch based on the types of all arguments to the call, as compared to functions in Python, which have a single implementation and no polymorphism (as opposed to Python method calls which use a different syntax and allows dispatch on the receiver of the method).
- There are no classes in Julia. Instead there are structures (mutable or immutable), containing data but no methods.
- Calling a method of a class instance in Python (
x = MyClass(*args); x.f(y)
) corresponds to a function call in Julia, e.g.x = MyType(args...); f(x, y)
. In general, multiple dispatch is more flexible and powerful than the Python class system. - Julia structures may have exactly one abstract supertype, whereas Python classes can inherit from one or more (abstract or concrete) superclasses.
- The logical Julia program structure (Packages and Modules) is independent of the file structure (
include
for additional files), whereas the Python code structure is defined by directories (Packages) and files (Modules). - The ternary operator
x > 0 ? 1 : -1
in Julia corresponds to a conditional expression in Python1 if x > 0 else -1
. - In Julia the
@
symbol refers to a macro, whereas in Python it refers to a decorator. - Exception handling in Julia is done using
try
—catch
—finally
, instead oftry
—except
—finally
. In contrast to Python, it is not recommended to use exception handling as part of the normal workflow in Julia (compared with Python, Julia is faster at ordinary control flow but slower at exception-catching). - In Julia loops are fast, there is no need to write “vectorized” code for performance reasons.
- Be careful with non-constant global variables in Julia, especially in tight loops. Since you can write close-to-metal code in Julia (unlike Python), the effect of globals can be drastic (seePerformance Tips).
- In Julia, rounding and truncation are explicit. Python’s
int(3.7)
should befloor(Int, 3.7)
orInt(floor(3.7))
and is distinguished fromround(Int, 3.7)
.floor(x)
andround(x)
on their own return an integer value of the same type asx
rather than always returningInt
. - In Julia, parsing is explicit. Python’s
float("3.7")
would beparse(Float64, "3.7")
in Julia. - In Python, the majority of values can be used in logical contexts (e.g.
if "a":
means the following block is executed, andif "":
means it is not). In Julia, you need explicit conversion toBool
(e.g.if "a"
throws an exception). If you want to test for a non-empty string in Julia, you would explicitly writeif !isempty("")
. Perhaps surprisingly, in Pythonif "False"
andbool("False")
both evaluate toTrue
(because"False"
is a non-empty string); in Julia,parse(Bool, "false")
returnsfalse
. - In Julia, a new local scope is introduced by most code blocks, including loops and
try
—catch
—finally
. Note that comprehensions (list, generator, etc.) introduce a new local scope both in Python and Julia, whereasif
blocks do not introduce a new local scope in both languages.
Noteworthy differences from Python
How does Julia’s denote a null value compared to Python?
Noteworthy differences from Python
- Julia’s
for
,if
,while
, etc. blocks are terminated by theend
keyword. Indentation level is not significant as it is in Python. Unlike Python, Julia has nopass
keyword. - Strings are denoted by double quotation marks (
"text"
) in Julia (with three double quotation marks for multi-line strings), whereas in Python they can be denoted either by single ('text'
) or double quotation marks ("text"
). Single quotation marks are used for characters in Julia ('c'
). - String concatenation is done with
*
in Julia, not+
like in Python. Analogously, string repetition is done with^
, not*
. Implicit string concatenation of string literals like in Python (e.g.'ab' 'cd' == 'abcd'
) is not done in Julia. - Python Lists—flexible but slow—correspond to the Julia
Vector{Any}
type or more generallyVector{T}
whereT
is some non-concrete element type. “Fast” arrays like NumPy arrays that store elements in-place (i.e.,dtype
isnp.float64
,[('f1', np.uint64), ('f2', np.int32)]
, etc.) can be represented byArray{T}
whereT
is a concrete, immutable element type. This includes built-in types likeFloat64
,Int32
,Int64
but also more complex types likeTuple{UInt64,Float64}
and many user-defined types as well. - In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.
- Julia’s slice indexing includes the last element, unlike in Python.
a[2:3]
in Julia isa[1:3]
in Python. - Unlike Python, Julia allowsAbstractArrays with arbitrary indexes. Python’s special interpretation of negative indexing,
a[-1]
anda[-2]
, should be writtena[end]
anda[end-1]
in Julia. - Julia requires
end
for indexing until the last element.x[1:]
in Python is equivalent tox[2:end]
in Julia. - In Julia,
:
before any object creates aSymbol
or_quotes_an expression; so,x[:5]
is same asx[5]
. If you want to get the firstn
elements of an array, then use range indexing. - Julia’s range indexing has the format of
x[start:step:stop]
, whereas Python’s format isx[start:(stop+1):step]
. Hence,x[0:10:2]
in Python is equivalent tox[1:2:10]
in Julia. Similarly,x[::-1]
in Python, which refers to the reversed array, is equivalent tox[end:-1:1]
in Julia. - In Julia, ranges can be constructed independently as
start:step:stop
, the same syntax it uses in array-indexing. Therange
function is also supported. - In Julia, indexing a matrix with arrays like
X[[1,2], [1,3]]
refers to a sub-matrix that contains the intersections of the first and second rows with the first and third columns. In Python,X[[1,2], [1,3]]
refers to a vector that contains the values of cell[1,1]
and[2,3]
in the matrix.X[[1,2], [1,3]]
in Julia is equivalent withX[np.ix_([0,1],[0,2])]
in Python.X[[0,1], [0,2]]
in Python is equivalent withX[[CartesianIndex(1,1), CartesianIndex(2,3)]]
in Julia. - Julia has no line continuation syntax: if, at the end of a line, the input so far is a complete expression, it is considered done; otherwise the input continues. One way to force an expression to continue is to wrap it in parentheses.
- Julia arrays are column-major (Fortran-ordered) whereas NumPy arrays are row-major (C-ordered) by default. To get optimal performance when looping over arrays, the order of the loops should be reversed in Julia relative to NumPy (seerelevant section of Performance Tips).
- Julia’s updating operators (e.g.
+=
,-=
, …) are_not in-place_whereas NumPy’s are. This meansA = [1, 1]; B = A; B += [3, 3]
doesn’t change values inA
, it rather rebinds the nameB
to the result of the right-hand sideB = B + 3
, which is a new array. For in-place operation, useB .+= 3
(see alsodot operators), explicit loops, orInplaceOps.jl
. - Julia evaluates default values of function arguments every time the method is invoked, unlike in Python where the default values are evaluated only once when the function is defined. For example, the function
f(x=rand()) = x
returns a new random number every time it is invoked without argument. On the other hand, the functiong(x=[1,2]) = push!(x,3)
returns[1,2,3]
every time it is called asg()
. - In Julia, keyword arguments must be passed using keywords, unlike Python in which it is usually possible to pass them positionally. Attempting to pass a keyword argument positionally alters the method signature leading to a
MethodError
or calling of the wrong method. - In Julia
%
is the remainder operator, whereas in Python it is the modulus. - In Julia, the commonly used
Int
type corresponds to the machine integer type (Int32
orInt64
), unlike in Python, whereint
is an arbitrary length integer. This means in Julia theInt
type will overflow, such that2^64 == 0
. If you need larger values use another appropriate type, such asInt128
,BigInt
or a floating point type likeFloat64
. - The imaginary unit
sqrt(-1)
is represented in Julia asim
, notj
as in Python. - In Julia, the exponentiation operator is
^
, not**
as in Python. - Julia uses
nothing
of typeNothing
to represent a null value, whereas Python usesNone
of typeNoneType
. - In Julia, the standard operators over a matrix type are matrix operations, whereas, in Python, the standard operators are element-wise operations. When both
A
andB
are matrices,A * B
in Julia performs matrix multiplication, not element-wise multiplication as in Python.A * B
in Julia is equivalent withA @ B
in Python, whereasA * B
in Python is equivalent withA .* B
in Julia. - The adjoint operator
'
in Julia returns an adjoint of a vector (a lazy representation of row vector), whereas the transpose operator.T
over a vector in Python returns the original vector (non-op). - In Julia, a function may contain multiple concrete implementations (called_methods_), which are selected via multiple dispatch based on the types of all arguments to the call, as compared to functions in Python, which have a single implementation and no polymorphism (as opposed to Python method calls which use a different syntax and allows dispatch on the receiver of the method).
- There are no classes in Julia. Instead there are structures (mutable or immutable), containing data but no methods.
- Calling a method of a class instance in Python (
x = MyClass(*args); x.f(y)
) corresponds to a function call in Julia, e.g.x = MyType(args...); f(x, y)
. In general, multiple dispatch is more flexible and powerful than the Python class system. - Julia structures may have exactly one abstract supertype, whereas Python classes can inherit from one or more (abstract or concrete) superclasses.
- The logical Julia program structure (Packages and Modules) is independent of the file structure (
include
for additional files), whereas the Python code structure is defined by directories (Packages) and files (Modules). - The ternary operator
x > 0 ? 1 : -1
in Julia corresponds to a conditional expression in Python1 if x > 0 else -1
. - In Julia the
@
symbol refers to a macro, whereas in Python it refers to a decorator. - Exception handling in Julia is done using
try
—catch
—finally
, instead oftry
—except
—finally
. In contrast to Python, it is not recommended to use exception handling as part of the normal workflow in Julia (compared with Python, Julia is faster at ordinary control flow but slower at exception-catching). - In Julia loops are fast, there is no need to write “vectorized” code for performance reasons.
- Be careful with non-constant global variables in Julia, especially in tight loops. Since you can write close-to-metal code in Julia (unlike Python), the effect of globals can be drastic (seePerformance Tips).
- In Julia, rounding and truncation are explicit. Python’s
int(3.7)
should befloor(Int, 3.7)
orInt(floor(3.7))
and is distinguished fromround(Int, 3.7)
.floor(x)
andround(x)
on their own return an integer value of the same type asx
rather than always returningInt
. - In Julia, parsing is explicit. Python’s
float("3.7")
would beparse(Float64, "3.7")
in Julia. - In Python, the majority of values can be used in logical contexts (e.g.
if "a":
means the following block is executed, andif "":
means it is not). In Julia, you need explicit conversion toBool
(e.g.if "a"
throws an exception). If you want to test for a non-empty string in Julia, you would explicitly writeif !isempty("")
. Perhaps surprisingly, in Pythonif "False"
andbool("False")
both evaluate toTrue
(because"False"
is a non-empty string); in Julia,parse(Bool, "false")
returnsfalse
. - In Julia, a new local scope is introduced by most code blocks, including loops and
try
—catch
—finally
. Note that comprehensions (list, generator, etc.) introduce a new local scope both in Python and Julia, whereasif
blocks do not introduce a new local scope in both languages.
Noteworthy differences from Python
How do functions in Julia and Python differ?
Noteworthy differences from Python
- Julia’s
for
,if
,while
, etc. blocks are terminated by theend
keyword. Indentation level is not significant as it is in Python. Unlike Python, Julia has nopass
keyword. - Strings are denoted by double quotation marks (
"text"
) in Julia (with three double quotation marks for multi-line strings), whereas in Python they can be denoted either by single ('text'
) or double quotation marks ("text"
). Single quotation marks are used for characters in Julia ('c'
). - String concatenation is done with
*
in Julia, not+
like in Python. Analogously, string repetition is done with^
, not*
. Implicit string concatenation of string literals like in Python (e.g.'ab' 'cd' == 'abcd'
) is not done in Julia. - Python Lists—flexible but slow—correspond to the Julia
Vector{Any}
type or more generallyVector{T}
whereT
is some non-concrete element type. “Fast” arrays like NumPy arrays that store elements in-place (i.e.,dtype
isnp.float64
,[('f1', np.uint64), ('f2', np.int32)]
, etc.) can be represented byArray{T}
whereT
is a concrete, immutable element type. This includes built-in types likeFloat64
,Int32
,Int64
but also more complex types likeTuple{UInt64,Float64}
and many user-defined types as well. - In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.
- Julia’s slice indexing includes the last element, unlike in Python.
a[2:3]
in Julia isa[1:3]
in Python. - Unlike Python, Julia allowsAbstractArrays with arbitrary indexes. Python’s special interpretation of negative indexing,
a[-1]
anda[-2]
, should be writtena[end]
anda[end-1]
in Julia. - Julia requires
end
for indexing until the last element.x[1:]
in Python is equivalent tox[2:end]
in Julia. - In Julia,
:
before any object creates aSymbol
or_quotes_an expression; so,x[:5]
is same asx[5]
. If you want to get the firstn
elements of an array, then use range indexing. - Julia’s range indexing has the format of
x[start:step:stop]
, whereas Python’s format isx[start:(stop+1):step]
. Hence,x[0:10:2]
in Python is equivalent tox[1:2:10]
in Julia. Similarly,x[::-1]
in Python, which refers to the reversed array, is equivalent tox[end:-1:1]
in Julia. - In Julia, ranges can be constructed independently as
start:step:stop
, the same syntax it uses in array-indexing. Therange
function is also supported. - In Julia, indexing a matrix with arrays like
X[[1,2], [1,3]]
refers to a sub-matrix that contains the intersections of the first and second rows with the first and third columns. In Python,X[[1,2], [1,3]]
refers to a vector that contains the values of cell[1,1]
and[2,3]
in the matrix.X[[1,2], [1,3]]
in Julia is equivalent withX[np.ix_([0,1],[0,2])]
in Python.X[[0,1], [0,2]]
in Python is equivalent withX[[CartesianIndex(1,1), CartesianIndex(2,3)]]
in Julia. - Julia has no line continuation syntax: if, at the end of a line, the input so far is a complete expression, it is considered done; otherwise the input continues. One way to force an expression to continue is to wrap it in parentheses.
- Julia arrays are column-major (Fortran-ordered) whereas NumPy arrays are row-major (C-ordered) by default. To get optimal performance when looping over arrays, the order of the loops should be reversed in Julia relative to NumPy (seerelevant section of Performance Tips).
- Julia’s updating operators (e.g.
+=
,-=
, …) are_not in-place_whereas NumPy’s are. This meansA = [1, 1]; B = A; B += [3, 3]
doesn’t change values inA
, it rather rebinds the nameB
to the result of the right-hand sideB = B + 3
, which is a new array. For in-place operation, useB .+= 3
(see alsodot operators), explicit loops, orInplaceOps.jl
. - Julia evaluates default values of function arguments every time the method is invoked, unlike in Python where the default values are evaluated only once when the function is defined. For example, the function
f(x=rand()) = x
returns a new random number every time it is invoked without argument. On the other hand, the functiong(x=[1,2]) = push!(x,3)
returns[1,2,3]
every time it is called asg()
. - In Julia, keyword arguments must be passed using keywords, unlike Python in which it is usually possible to pass them positionally. Attempting to pass a keyword argument positionally alters the method signature leading to a
MethodError
or calling of the wrong method. - In Julia
%
is the remainder operator, whereas in Python it is the modulus. - In Julia, the commonly used
Int
type corresponds to the machine integer type (Int32
orInt64
), unlike in Python, whereint
is an arbitrary length integer. This means in Julia theInt
type will overflow, such that2^64 == 0
. If you need larger values use another appropriate type, such asInt128
,BigInt
or a floating point type likeFloat64
. - The imaginary unit
sqrt(-1)
is represented in Julia asim
, notj
as in Python. - In Julia, the exponentiation operator is
^
, not**
as in Python. - Julia uses
nothing
of typeNothing
to represent a null value, whereas Python usesNone
of typeNoneType
. - In Julia, the standard operators over a matrix type are matrix operations, whereas, in Python, the standard operators are element-wise operations. When both
A
andB
are matrices,A * B
in Julia performs matrix multiplication, not element-wise multiplication as in Python.A * B
in Julia is equivalent withA @ B
in Python, whereasA * B
in Python is equivalent withA .* B
in Julia. - The adjoint operator
'
in Julia returns an adjoint of a vector (a lazy representation of row vector), whereas the transpose operator.T
over a vector in Python returns the original vector (non-op). - In Julia, a function may contain multiple concrete implementations (called_methods_), which are selected via multiple dispatch based on the types of all arguments to the call, as compared to functions in Python, which have a single implementation and no polymorphism (as opposed to Python method calls which use a different syntax and allows dispatch on the receiver of the method).
- There are no classes in Julia. Instead there are structures (mutable or immutable), containing data but no methods.
- Calling a method of a class instance in Python (
x = MyClass(*args); x.f(y)
) corresponds to a function call in Julia, e.g.x = MyType(args...); f(x, y)
. In general, multiple dispatch is more flexible and powerful than the Python class system. - Julia structures may have exactly one abstract supertype, whereas Python classes can inherit from one or more (abstract or concrete) superclasses.
- The logical Julia program structure (Packages and Modules) is independent of the file structure (
include
for additional files), whereas the Python code structure is defined by directories (Packages) and files (Modules). - The ternary operator
x > 0 ? 1 : -1
in Julia corresponds to a conditional expression in Python1 if x > 0 else -1
. - In Julia the
@
symbol refers to a macro, whereas in Python it refers to a decorator. - Exception handling in Julia is done using
try
—catch
—finally
, instead oftry
—except
—finally
. In contrast to Python, it is not recommended to use exception handling as part of the normal workflow in Julia (compared with Python, Julia is faster at ordinary control flow but slower at exception-catching). - In Julia loops are fast, there is no need to write “vectorized” code for performance reasons.
- Be careful with non-constant global variables in Julia, especially in tight loops. Since you can write close-to-metal code in Julia (unlike Python), the effect of globals can be drastic (seePerformance Tips).
- In Julia, rounding and truncation are explicit. Python’s
int(3.7)
should befloor(Int, 3.7)
orInt(floor(3.7))
and is distinguished fromround(Int, 3.7)
.floor(x)
andround(x)
on their own return an integer value of the same type asx
rather than always returningInt
. - In Julia, parsing is explicit. Python’s
float("3.7")
would beparse(Float64, "3.7")
in Julia. - In Python, the majority of values can be used in logical contexts (e.g.
if "a":
means the following block is executed, andif "":
means it is not). In Julia, you need explicit conversion toBool
(e.g.if "a"
throws an exception). If you want to test for a non-empty string in Julia, you would explicitly writeif !isempty("")
. Perhaps surprisingly, in Pythonif "False"
andbool("False")
both evaluate toTrue
(because"False"
is a non-empty string); in Julia,parse(Bool, "false")
returnsfalse
. - In Julia, a new local scope is introduced by most code blocks, including loops and
try
—catch
—finally
. Note that comprehensions (list, generator, etc.) introduce a new local scope both in Python and Julia, whereasif
blocks do not introduce a new local scope in both languages.
Noteworthy differences from Python
How doe classes in Julia differ from Python?
Noteworthy differences from Python
- Julia’s
for
,if
,while
, etc. blocks are terminated by theend
keyword. Indentation level is not significant as it is in Python. Unlike Python, Julia has nopass
keyword. - Strings are denoted by double quotation marks (
"text"
) in Julia (with three double quotation marks for multi-line strings), whereas in Python they can be denoted either by single ('text'
) or double quotation marks ("text"
). Single quotation marks are used for characters in Julia ('c'
). - String concatenation is done with
*
in Julia, not+
like in Python. Analogously, string repetition is done with^
, not*
. Implicit string concatenation of string literals like in Python (e.g.'ab' 'cd' == 'abcd'
) is not done in Julia. - Python Lists—flexible but slow—correspond to the Julia
Vector{Any}
type or more generallyVector{T}
whereT
is some non-concrete element type. “Fast” arrays like NumPy arrays that store elements in-place (i.e.,dtype
isnp.float64
,[('f1', np.uint64), ('f2', np.int32)]
, etc.) can be represented byArray{T}
whereT
is a concrete, immutable element type. This includes built-in types likeFloat64
,Int32
,Int64
but also more complex types likeTuple{UInt64,Float64}
and many user-defined types as well. - In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.
- Julia’s slice indexing includes the last element, unlike in Python.
a[2:3]
in Julia isa[1:3]
in Python. - Unlike Python, Julia allowsAbstractArrays with arbitrary indexes. Python’s special interpretation of negative indexing,
a[-1]
anda[-2]
, should be writtena[end]
anda[end-1]
in Julia. - Julia requires
end
for indexing until the last element.x[1:]
in Python is equivalent tox[2:end]
in Julia. - In Julia,
:
before any object creates aSymbol
or_quotes_an expression; so,x[:5]
is same asx[5]
. If you want to get the firstn
elements of an array, then use range indexing. - Julia’s range indexing has the format of
x[start:step:stop]
, whereas Python’s format isx[start:(stop+1):step]
. Hence,x[0:10:2]
in Python is equivalent tox[1:2:10]
in Julia. Similarly,x[::-1]
in Python, which refers to the reversed array, is equivalent tox[end:-1:1]
in Julia. - In Julia, ranges can be constructed independently as
start:step:stop
, the same syntax it uses in array-indexing. Therange
function is also supported. - In Julia, indexing a matrix with arrays like
X[[1,2], [1,3]]
refers to a sub-matrix that contains the intersections of the first and second rows with the first and third columns. In Python,X[[1,2], [1,3]]
refers to a vector that contains the values of cell[1,1]
and[2,3]
in the matrix.X[[1,2], [1,3]]
in Julia is equivalent withX[np.ix_([0,1],[0,2])]
in Python.X[[0,1], [0,2]]
in Python is equivalent withX[[CartesianIndex(1,1), CartesianIndex(2,3)]]
in Julia. - Julia has no line continuation syntax: if, at the end of a line, the input so far is a complete expression, it is considered done; otherwise the input continues. One way to force an expression to continue is to wrap it in parentheses.
- Julia arrays are column-major (Fortran-ordered) whereas NumPy arrays are row-major (C-ordered) by default. To get optimal performance when looping over arrays, the order of the loops should be reversed in Julia relative to NumPy (seerelevant section of Performance Tips).
- Julia’s updating operators (e.g.
+=
,-=
, …) are_not in-place_whereas NumPy’s are. This meansA = [1, 1]; B = A; B += [3, 3]
doesn’t change values inA
, it rather rebinds the nameB
to the result of the right-hand sideB = B + 3
, which is a new array. For in-place operation, useB .+= 3
(see alsodot operators), explicit loops, orInplaceOps.jl
. - Julia evaluates default values of function arguments every time the method is invoked, unlike in Python where the default values are evaluated only once when the function is defined. For example, the function
f(x=rand()) = x
returns a new random number every time it is invoked without argument. On the other hand, the functiong(x=[1,2]) = push!(x,3)
returns[1,2,3]
every time it is called asg()
. - In Julia, keyword arguments must be passed using keywords, unlike Python in which it is usually possible to pass them positionally. Attempting to pass a keyword argument positionally alters the method signature leading to a
MethodError
or calling of the wrong method. - In Julia
%
is the remainder operator, whereas in Python it is the modulus. - In Julia, the commonly used
Int
type corresponds to the machine integer type (Int32
orInt64
), unlike in Python, whereint
is an arbitrary length integer. This means in Julia theInt
type will overflow, such that2^64 == 0
. If you need larger values use another appropriate type, such asInt128
,BigInt
or a floating point type likeFloat64
. - The imaginary unit
sqrt(-1)
is represented in Julia asim
, notj
as in Python. - In Julia, the exponentiation operator is
^
, not**
as in Python. - Julia uses
nothing
of typeNothing
to represent a null value, whereas Python usesNone
of typeNoneType
. - In Julia, the standard operators over a matrix type are matrix operations, whereas, in Python, the standard operators are element-wise operations. When both
A
andB
are matrices,A * B
in Julia performs matrix multiplication, not element-wise multiplication as in Python.A * B
in Julia is equivalent withA @ B
in Python, whereasA * B
in Python is equivalent withA .* B
in Julia. - The adjoint operator
'
in Julia returns an adjoint of a vector (a lazy representation of row vector), whereas the transpose operator.T
over a vector in Python returns the original vector (non-op). - In Julia, a function may contain multiple concrete implementations (called_methods_), which are selected via multiple dispatch based on the types of all arguments to the call, as compared to functions in Python, which have a single implementation and no polymorphism (as opposed to Python method calls which use a different syntax and allows dispatch on the receiver of the method).
- There are no classes in Julia. Instead there are structures (mutable or immutable), containing data but no methods.
- Calling a method of a class instance in Python (
x = MyClass(*args); x.f(y)
) corresponds to a function call in Julia, e.g.x = MyType(args...); f(x, y)
. In general, multiple dispatch is more flexible and powerful than the Python class system. - Julia structures may have exactly one abstract supertype, whereas Python classes can inherit from one or more (abstract or concrete) superclasses.
- The logical Julia program structure (Packages and Modules) is independent of the file structure (
include
for additional files), whereas the Python code structure is defined by directories (Packages) and files (Modules). - The ternary operator
x > 0 ? 1 : -1
in Julia corresponds to a conditional expression in Python1 if x > 0 else -1
. - In Julia the
@
symbol refers to a macro, whereas in Python it refers to a decorator. - Exception handling in Julia is done using
try
—catch
—finally
, instead oftry
—except
—finally
. In contrast to Python, it is not recommended to use exception handling as part of the normal workflow in Julia (compared with Python, Julia is faster at ordinary control flow but slower at exception-catching). - In Julia loops are fast, there is no need to write “vectorized” code for performance reasons.
- Be careful with non-constant global variables in Julia, especially in tight loops. Since you can write close-to-metal code in Julia (unlike Python), the effect of globals can be drastic (seePerformance Tips).
- In Julia, rounding and truncation are explicit. Python’s
int(3.7)
should befloor(Int, 3.7)
orInt(floor(3.7))
and is distinguished fromround(Int, 3.7)
.floor(x)
andround(x)
on their own return an integer value of the same type asx
rather than always returningInt
. - In Julia, parsing is explicit. Python’s
float("3.7")
would beparse(Float64, "3.7")
in Julia. - In Python, the majority of values can be used in logical contexts (e.g.
if "a":
means the following block is executed, andif "":
means it is not). In Julia, you need explicit conversion toBool
(e.g.if "a"
throws an exception). If you want to test for a non-empty string in Julia, you would explicitly writeif !isempty("")
. Perhaps surprisingly, in Pythonif "False"
andbool("False")
both evaluate toTrue
(because"False"
is a non-empty string); in Julia,parse(Bool, "false")
returnsfalse
. - In Julia, a new local scope is introduced by most code blocks, including loops and
try
—catch
—finally
. Note that comprehensions (list, generator, etc.) introduce a new local scope both in Python and Julia, whereasif
blocks do not introduce a new local scope in both languages.
Noteworthy differences from Python
How many supertypes can Julia have compared to Python?
Noteworthy differences from Python
- Julia’s
for
,if
,while
, etc. blocks are terminated by theend
keyword. Indentation level is not significant as it is in Python. Unlike Python, Julia has nopass
keyword. - Strings are denoted by double quotation marks (
"text"
) in Julia (with three double quotation marks for multi-line strings), whereas in Python they can be denoted either by single ('text'
) or double quotation marks ("text"
). Single quotation marks are used for characters in Julia ('c'
). - String concatenation is done with
*
in Julia, not+
like in Python. Analogously, string repetition is done with^
, not*
. Implicit string concatenation of string literals like in Python (e.g.'ab' 'cd' == 'abcd'
) is not done in Julia. - Python Lists—flexible but slow—correspond to the Julia
Vector{Any}
type or more generallyVector{T}
whereT
is some non-concrete element type. “Fast” arrays like NumPy arrays that store elements in-place (i.e.,dtype
isnp.float64
,[('f1', np.uint64), ('f2', np.int32)]
, etc.) can be represented byArray{T}
whereT
is a concrete, immutable element type. This includes built-in types likeFloat64
,Int32
,Int64
but also more complex types likeTuple{UInt64,Float64}
and many user-defined types as well. - In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.
- Julia’s slice indexing includes the last element, unlike in Python.
a[2:3]
in Julia isa[1:3]
in Python. - Unlike Python, Julia allowsAbstractArrays with arbitrary indexes. Python’s special interpretation of negative indexing,
a[-1]
anda[-2]
, should be writtena[end]
anda[end-1]
in Julia. - Julia requires
end
for indexing until the last element.x[1:]
in Python is equivalent tox[2:end]
in Julia. - In Julia,
:
before any object creates aSymbol
or_quotes_an expression; so,x[:5]
is same asx[5]
. If you want to get the firstn
elements of an array, then use range indexing. - Julia’s range indexing has the format of
x[start:step:stop]
, whereas Python’s format isx[start:(stop+1):step]
. Hence,x[0:10:2]
in Python is equivalent tox[1:2:10]
in Julia. Similarly,x[::-1]
in Python, which refers to the reversed array, is equivalent tox[end:-1:1]
in Julia. - In Julia, ranges can be constructed independently as
start:step:stop
, the same syntax it uses in array-indexing. Therange
function is also supported. - In Julia, indexing a matrix with arrays like
X[[1,2], [1,3]]
refers to a sub-matrix that contains the intersections of the first and second rows with the first and third columns. In Python,X[[1,2], [1,3]]
refers to a vector that contains the values of cell[1,1]
and[2,3]
in the matrix.X[[1,2], [1,3]]
in Julia is equivalent withX[np.ix_([0,1],[0,2])]
in Python.X[[0,1], [0,2]]
in Python is equivalent withX[[CartesianIndex(1,1), CartesianIndex(2,3)]]
in Julia. - Julia has no line continuation syntax: if, at the end of a line, the input so far is a complete expression, it is considered done; otherwise the input continues. One way to force an expression to continue is to wrap it in parentheses.
- Julia arrays are column-major (Fortran-ordered) whereas NumPy arrays are row-major (C-ordered) by default. To get optimal performance when looping over arrays, the order of the loops should be reversed in Julia relative to NumPy (seerelevant section of Performance Tips).
- Julia’s updating operators (e.g.
+=
,-=
, …) are_not in-place_whereas NumPy’s are. This meansA = [1, 1]; B = A; B += [3, 3]
doesn’t change values inA
, it rather rebinds the nameB
to the result of the right-hand sideB = B + 3
, which is a new array. For in-place operation, useB .+= 3
(see alsodot operators), explicit loops, orInplaceOps.jl
. - Julia evaluates default values of function arguments every time the method is invoked, unlike in Python where the default values are evaluated only once when the function is defined. For example, the function
f(x=rand()) = x
returns a new random number every time it is invoked without argument. On the other hand, the functiong(x=[1,2]) = push!(x,3)
returns[1,2,3]
every time it is called asg()
. - In Julia, keyword arguments must be passed using keywords, unlike Python in which it is usually possible to pass them positionally. Attempting to pass a keyword argument positionally alters the method signature leading to a
MethodError
or calling of the wrong method. - In Julia
%
is the remainder operator, whereas in Python it is the modulus. - In Julia, the commonly used
Int
type corresponds to the machine integer type (Int32
orInt64
), unlike in Python, whereint
is an arbitrary length integer. This means in Julia theInt
type will overflow, such that2^64 == 0
. If you need larger values use another appropriate type, such asInt128
,BigInt
or a floating point type likeFloat64
. - The imaginary unit
sqrt(-1)
is represented in Julia asim
, notj
as in Python. - In Julia, the exponentiation operator is
^
, not**
as in Python. - Julia uses
nothing
of typeNothing
to represent a null value, whereas Python usesNone
of typeNoneType
. - In Julia, the standard operators over a matrix type are matrix operations, whereas, in Python, the standard operators are element-wise operations. When both
A
andB
are matrices,A * B
in Julia performs matrix multiplication, not element-wise multiplication as in Python.A * B
in Julia is equivalent withA @ B
in Python, whereasA * B
in Python is equivalent withA .* B
in Julia. - The adjoint operator
'
in Julia returns an adjoint of a vector (a lazy representation of row vector), whereas the transpose operator.T
over a vector in Python returns the original vector (non-op). - In Julia, a function may contain multiple concrete implementations (called_methods_), which are selected via multiple dispatch based on the types of all arguments to the call, as compared to functions in Python, which have a single implementation and no polymorphism (as opposed to Python method calls which use a different syntax and allows dispatch on the receiver of the method).
- There are no classes in Julia. Instead there are structures (mutable or immutable), containing data but no methods.
- Calling a method of a class instance in Python (
x = MyClass(*args); x.f(y)
) corresponds to a function call in Julia, e.g.x = MyType(args...); f(x, y)
. In general, multiple dispatch is more flexible and powerful than the Python class system. - Julia structures may have exactly one abstract supertype, whereas Python classes can inherit from one or more (abstract or concrete) superclasses.
- The logical Julia program structure (Packages and Modules) is independent of the file structure (
include
for additional files), whereas the Python code structure is defined by directories (Packages) and files (Modules). - The ternary operator
x > 0 ? 1 : -1
in Julia corresponds to a conditional expression in Python1 if x > 0 else -1
. - In Julia the
@
symbol refers to a macro, whereas in Python it refers to a decorator. - Exception handling in Julia is done using
try
—catch
—finally
, instead oftry
—except
—finally
. In contrast to Python, it is not recommended to use exception handling as part of the normal workflow in Julia (compared with Python, Julia is faster at ordinary control flow but slower at exception-catching). - In Julia loops are fast, there is no need to write “vectorized” code for performance reasons.
- Be careful with non-constant global variables in Julia, especially in tight loops. Since you can write close-to-metal code in Julia (unlike Python), the effect of globals can be drastic (seePerformance Tips).
- In Julia, rounding and truncation are explicit. Python’s
int(3.7)
should befloor(Int, 3.7)
orInt(floor(3.7))
and is distinguished fromround(Int, 3.7)
.floor(x)
andround(x)
on their own return an integer value of the same type asx
rather than always returningInt
. - In Julia, parsing is explicit. Python’s
float("3.7")
would beparse(Float64, "3.7")
in Julia. - In Python, the majority of values can be used in logical contexts (e.g.
if "a":
means the following block is executed, andif "":
means it is not). In Julia, you need explicit conversion toBool
(e.g.if "a"
throws an exception). If you want to test for a non-empty string in Julia, you would explicitly writeif !isempty("")
. Perhaps surprisingly, in Pythonif "False"
andbool("False")
both evaluate toTrue
(because"False"
is a non-empty string); in Julia,parse(Bool, "false")
returnsfalse
. - In Julia, a new local scope is introduced by most code blocks, including loops and
try
—catch
—finally
. Note that comprehensions (list, generator, etc.) introduce a new local scope both in Python and Julia, whereasif
blocks do not introduce a new local scope in both languages.
Noteworthy differences from Python
How does the ternary operator differ between Julia and Python?
Noteworthy differences from Python
- Julia’s
for
,if
,while
, etc. blocks are terminated by theend
keyword. Indentation level is not significant as it is in Python. Unlike Python, Julia has nopass
keyword. - Strings are denoted by double quotation marks (
"text"
) in Julia (with three double quotation marks for multi-line strings), whereas in Python they can be denoted either by single ('text'
) or double quotation marks ("text"
). Single quotation marks are used for characters in Julia ('c'
). - String concatenation is done with
*
in Julia, not+
like in Python. Analogously, string repetition is done with^
, not*
. Implicit string concatenation of string literals like in Python (e.g.'ab' 'cd' == 'abcd'
) is not done in Julia. - Python Lists—flexible but slow—correspond to the Julia
Vector{Any}
type or more generallyVector{T}
whereT
is some non-concrete element type. “Fast” arrays like NumPy arrays that store elements in-place (i.e.,dtype
isnp.float64
,[('f1', np.uint64), ('f2', np.int32)]
, etc.) can be represented byArray{T}
whereT
is a concrete, immutable element type. This includes built-in types likeFloat64
,Int32
,Int64
but also more complex types likeTuple{UInt64,Float64}
and many user-defined types as well. - In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.
- Julia’s slice indexing includes the last element, unlike in Python.
a[2:3]
in Julia isa[1:3]
in Python. - Unlike Python, Julia allowsAbstractArrays with arbitrary indexes. Python’s special interpretation of negative indexing,
a[-1]
anda[-2]
, should be writtena[end]
anda[end-1]
in Julia. - Julia requires
end
for indexing until the last element.x[1:]
in Python is equivalent tox[2:end]
in Julia. - In Julia,
:
before any object creates aSymbol
or_quotes_an expression; so,x[:5]
is same asx[5]
. If you want to get the firstn
elements of an array, then use range indexing. - Julia’s range indexing has the format of
x[start:step:stop]
, whereas Python’s format isx[start:(stop+1):step]
. Hence,x[0:10:2]
in Python is equivalent tox[1:2:10]
in Julia. Similarly,x[::-1]
in Python, which refers to the reversed array, is equivalent tox[end:-1:1]
in Julia. - In Julia, ranges can be constructed independently as
start:step:stop
, the same syntax it uses in array-indexing. Therange
function is also supported. - In Julia, indexing a matrix with arrays like
X[[1,2], [1,3]]
refers to a sub-matrix that contains the intersections of the first and second rows with the first and third columns. In Python,X[[1,2], [1,3]]
refers to a vector that contains the values of cell[1,1]
and[2,3]
in the matrix.X[[1,2], [1,3]]
in Julia is equivalent withX[np.ix_([0,1],[0,2])]
in Python.X[[0,1], [0,2]]
in Python is equivalent withX[[CartesianIndex(1,1), CartesianIndex(2,3)]]
in Julia. - Julia has no line continuation syntax: if, at the end of a line, the input so far is a complete expression, it is considered done; otherwise the input continues. One way to force an expression to continue is to wrap it in parentheses.
- Julia arrays are column-major (Fortran-ordered) whereas NumPy arrays are row-major (C-ordered) by default. To get optimal performance when looping over arrays, the order of the loops should be reversed in Julia relative to NumPy (seerelevant section of Performance Tips).
- Julia’s updating operators (e.g.
+=
,-=
, …) are_not in-place_whereas NumPy’s are. This meansA = [1, 1]; B = A; B += [3, 3]
doesn’t change values inA
, it rather rebinds the nameB
to the result of the right-hand sideB = B + 3
, which is a new array. For in-place operation, useB .+= 3
(see alsodot operators), explicit loops, orInplaceOps.jl
. - Julia evaluates default values of function arguments every time the method is invoked, unlike in Python where the default values are evaluated only once when the function is defined. For example, the function
f(x=rand()) = x
returns a new random number every time it is invoked without argument. On the other hand, the functiong(x=[1,2]) = push!(x,3)
returns[1,2,3]
every time it is called asg()
. - In Julia, keyword arguments must be passed using keywords, unlike Python in which it is usually possible to pass them positionally. Attempting to pass a keyword argument positionally alters the method signature leading to a
MethodError
or calling of the wrong method. - In Julia
%
is the remainder operator, whereas in Python it is the modulus. - In Julia, the commonly used
Int
type corresponds to the machine integer type (Int32
orInt64
), unlike in Python, whereint
is an arbitrary length integer. This means in Julia theInt
type will overflow, such that2^64 == 0
. If you need larger values use another appropriate type, such asInt128
,BigInt
or a floating point type likeFloat64
. - The imaginary unit
sqrt(-1)
is represented in Julia asim
, notj
as in Python. - In Julia, the exponentiation operator is
^
, not**
as in Python. - Julia uses
nothing
of typeNothing
to represent a null value, whereas Python usesNone
of typeNoneType
. - In Julia, the standard operators over a matrix type are matrix operations, whereas, in Python, the standard operators are element-wise operations. When both
A
andB
are matrices,A * B
in Julia performs matrix multiplication, not element-wise multiplication as in Python.A * B
in Julia is equivalent withA @ B
in Python, whereasA * B
in Python is equivalent withA .* B
in Julia. - The adjoint operator
'
in Julia returns an adjoint of a vector (a lazy representation of row vector), whereas the transpose operator.T
over a vector in Python returns the original vector (non-op). - In Julia, a function may contain multiple concrete implementations (called_methods_), which are selected via multiple dispatch based on the types of all arguments to the call, as compared to functions in Python, which have a single implementation and no polymorphism (as opposed to Python method calls which use a different syntax and allows dispatch on the receiver of the method).
- There are no classes in Julia. Instead there are structures (mutable or immutable), containing data but no methods.
- Calling a method of a class instance in Python (
x = MyClass(*args); x.f(y)
) corresponds to a function call in Julia, e.g.x = MyType(args...); f(x, y)
. In general, multiple dispatch is more flexible and powerful than the Python class system. - Julia structures may have exactly one abstract supertype, whereas Python classes can inherit from one or more (abstract or concrete) superclasses.
- The logical Julia program structure (Packages and Modules) is independent of the file structure (
include
for additional files), whereas the Python code structure is defined by directories (Packages) and files (Modules). - The ternary operator
x > 0 ? 1 : -1
in Julia corresponds to a conditional expression in Python1 if x > 0 else -1
. - In Julia the
@
symbol refers to a macro, whereas in Python it refers to a decorator. - Exception handling in Julia is done using
try
—catch
—finally
, instead oftry
—except
—finally
. In contrast to Python, it is not recommended to use exception handling as part of the normal workflow in Julia (compared with Python, Julia is faster at ordinary control flow but slower at exception-catching). - In Julia loops are fast, there is no need to write “vectorized” code for performance reasons.
- Be careful with non-constant global variables in Julia, especially in tight loops. Since you can write close-to-metal code in Julia (unlike Python), the effect of globals can be drastic (seePerformance Tips).
- In Julia, rounding and truncation are explicit. Python’s
int(3.7)
should befloor(Int, 3.7)
orInt(floor(3.7))
and is distinguished fromround(Int, 3.7)
.floor(x)
andround(x)
on their own return an integer value of the same type asx
rather than always returningInt
. - In Julia, parsing is explicit. Python’s
float("3.7")
would beparse(Float64, "3.7")
in Julia. - In Python, the majority of values can be used in logical contexts (e.g.
if "a":
means the following block is executed, andif "":
means it is not). In Julia, you need explicit conversion toBool
(e.g.if "a"
throws an exception). If you want to test for a non-empty string in Julia, you would explicitly writeif !isempty("")
. Perhaps surprisingly, in Pythonif "False"
andbool("False")
both evaluate toTrue
(because"False"
is a non-empty string); in Julia,parse(Bool, "false")
returnsfalse
. - In Julia, a new local scope is introduced by most code blocks, including loops and
try
—catch
—finally
. Note that comprehensions (list, generator, etc.) introduce a new local scope both in Python and Julia, whereasif
blocks do not introduce a new local scope in both languages.
Noteworthy differences from Python
How do Julia and Python differ on the use of ‘ @ ‘?
Noteworthy differences from Python
- Julia’s
for
,if
,while
, etc. blocks are terminated by theend
keyword. Indentation level is not significant as it is in Python. Unlike Python, Julia has nopass
keyword. - Strings are denoted by double quotation marks (
"text"
) in Julia (with three double quotation marks for multi-line strings), whereas in Python they can be denoted either by single ('text'
) or double quotation marks ("text"
). Single quotation marks are used for characters in Julia ('c'
). - String concatenation is done with
*
in Julia, not+
like in Python. Analogously, string repetition is done with^
, not*
. Implicit string concatenation of string literals like in Python (e.g.'ab' 'cd' == 'abcd'
) is not done in Julia. - Python Lists—flexible but slow—correspond to the Julia
Vector{Any}
type or more generallyVector{T}
whereT
is some non-concrete element type. “Fast” arrays like NumPy arrays that store elements in-place (i.e.,dtype
isnp.float64
,[('f1', np.uint64), ('f2', np.int32)]
, etc.) can be represented byArray{T}
whereT
is a concrete, immutable element type. This includes built-in types likeFloat64
,Int32
,Int64
but also more complex types likeTuple{UInt64,Float64}
and many user-defined types as well. - In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.
- Julia’s slice indexing includes the last element, unlike in Python.
a[2:3]
in Julia isa[1:3]
in Python. - Unlike Python, Julia allowsAbstractArrays with arbitrary indexes. Python’s special interpretation of negative indexing,
a[-1]
anda[-2]
, should be writtena[end]
anda[end-1]
in Julia. - Julia requires
end
for indexing until the last element.x[1:]
in Python is equivalent tox[2:end]
in Julia. - In Julia,
:
before any object creates aSymbol
or_quotes_an expression; so,x[:5]
is same asx[5]
. If you want to get the firstn
elements of an array, then use range indexing. - Julia’s range indexing has the format of
x[start:step:stop]
, whereas Python’s format isx[start:(stop+1):step]
. Hence,x[0:10:2]
in Python is equivalent tox[1:2:10]
in Julia. Similarly,x[::-1]
in Python, which refers to the reversed array, is equivalent tox[end:-1:1]
in Julia. - In Julia, ranges can be constructed independently as
start:step:stop
, the same syntax it uses in array-indexing. Therange
function is also supported. - In Julia, indexing a matrix with arrays like
X[[1,2], [1,3]]
refers to a sub-matrix that contains the intersections of the first and second rows with the first and third columns. In Python,X[[1,2], [1,3]]
refers to a vector that contains the values of cell[1,1]
and[2,3]
in the matrix.X[[1,2], [1,3]]
in Julia is equivalent withX[np.ix_([0,1],[0,2])]
in Python.X[[0,1], [0,2]]
in Python is equivalent withX[[CartesianIndex(1,1), CartesianIndex(2,3)]]
in Julia. - Julia has no line continuation syntax: if, at the end of a line, the input so far is a complete expression, it is considered done; otherwise the input continues. One way to force an expression to continue is to wrap it in parentheses.
- Julia arrays are column-major (Fortran-ordered) whereas NumPy arrays are row-major (C-ordered) by default. To get optimal performance when looping over arrays, the order of the loops should be reversed in Julia relative to NumPy (seerelevant section of Performance Tips).
- Julia’s updating operators (e.g.
+=
,-=
, …) are_not in-place_whereas NumPy’s are. This meansA = [1, 1]; B = A; B += [3, 3]
doesn’t change values inA
, it rather rebinds the nameB
to the result of the right-hand sideB = B + 3
, which is a new array. For in-place operation, useB .+= 3
(see alsodot operators), explicit loops, orInplaceOps.jl
. - Julia evaluates default values of function arguments every time the method is invoked, unlike in Python where the default values are evaluated only once when the function is defined. For example, the function
f(x=rand()) = x
returns a new random number every time it is invoked without argument. On the other hand, the functiong(x=[1,2]) = push!(x,3)
returns[1,2,3]
every time it is called asg()
. - In Julia, keyword arguments must be passed using keywords, unlike Python in which it is usually possible to pass them positionally. Attempting to pass a keyword argument positionally alters the method signature leading to a
MethodError
or calling of the wrong method. - In Julia
%
is the remainder operator, whereas in Python it is the modulus. - In Julia, the commonly used
Int
type corresponds to the machine integer type (Int32
orInt64
), unlike in Python, whereint
is an arbitrary length integer. This means in Julia theInt
type will overflow, such that2^64 == 0
. If you need larger values use another appropriate type, such asInt128
,BigInt
or a floating point type likeFloat64
. - The imaginary unit
sqrt(-1)
is represented in Julia asim
, notj
as in Python. - In Julia, the exponentiation operator is
^
, not**
as in Python. - Julia uses
nothing
of typeNothing
to represent a null value, whereas Python usesNone
of typeNoneType
. - In Julia, the standard operators over a matrix type are matrix operations, whereas, in Python, the standard operators are element-wise operations. When both
A
andB
are matrices,A * B
in Julia performs matrix multiplication, not element-wise multiplication as in Python.A * B
in Julia is equivalent withA @ B
in Python, whereasA * B
in Python is equivalent withA .* B
in Julia. - The adjoint operator
'
in Julia returns an adjoint of a vector (a lazy representation of row vector), whereas the transpose operator.T
over a vector in Python returns the original vector (non-op). - In Julia, a function may contain multiple concrete implementations (called_methods_), which are selected via multiple dispatch based on the types of all arguments to the call, as compared to functions in Python, which have a single implementation and no polymorphism (as opposed to Python method calls which use a different syntax and allows dispatch on the receiver of the method).
- There are no classes in Julia. Instead there are structures (mutable or immutable), containing data but no methods.
- Calling a method of a class instance in Python (
x = MyClass(*args); x.f(y)
) corresponds to a function call in Julia, e.g.x = MyType(args...); f(x, y)
. In general, multiple dispatch is more flexible and powerful than the Python class system. - Julia structures may have exactly one abstract supertype, whereas Python classes can inherit from one or more (abstract or concrete) superclasses.
- The logical Julia program structure (Packages and Modules) is independent of the file structure (
include
for additional files), whereas the Python code structure is defined by directories (Packages) and files (Modules). - The ternary operator
x > 0 ? 1 : -1
in Julia corresponds to a conditional expression in Python1 if x > 0 else -1
. - In Julia the
@
symbol refers to a macro, whereas in Python it refers to a decorator. - Exception handling in Julia is done using
try
—catch
—finally
, instead oftry
—except
—finally
. In contrast to Python, it is not recommended to use exception handling as part of the normal workflow in Julia (compared with Python, Julia is faster at ordinary control flow but slower at exception-catching). - In Julia loops are fast, there is no need to write “vectorized” code for performance reasons.
- Be careful with non-constant global variables in Julia, especially in tight loops. Since you can write close-to-metal code in Julia (unlike Python), the effect of globals can be drastic (seePerformance Tips).
- In Julia, rounding and truncation are explicit. Python’s
int(3.7)
should befloor(Int, 3.7)
orInt(floor(3.7))
and is distinguished fromround(Int, 3.7)
.floor(x)
andround(x)
on their own return an integer value of the same type asx
rather than always returningInt
. - In Julia, parsing is explicit. Python’s
float("3.7")
would beparse(Float64, "3.7")
in Julia. - In Python, the majority of values can be used in logical contexts (e.g.
if "a":
means the following block is executed, andif "":
means it is not). In Julia, you need explicit conversion toBool
(e.g.if "a"
throws an exception). If you want to test for a non-empty string in Julia, you would explicitly writeif !isempty("")
. Perhaps surprisingly, in Pythonif "False"
andbool("False")
both evaluate toTrue
(because"False"
is a non-empty string); in Julia,parse(Bool, "false")
returnsfalse
. - In Julia, a new local scope is introduced by most code blocks, including loops and
try
—catch
—finally
. Note that comprehensions (list, generator, etc.) introduce a new local scope both in Python and Julia, whereasif
blocks do not introduce a new local scope in both languages.
Noteworthy differences from Python
How does Julia and Python differ on exception handling?
Noteworthy differences from Python
- Julia’s
for
,if
,while
, etc. blocks are terminated by theend
keyword. Indentation level is not significant as it is in Python. Unlike Python, Julia has nopass
keyword. - Strings are denoted by double quotation marks (
"text"
) in Julia (with three double quotation marks for multi-line strings), whereas in Python they can be denoted either by single ('text'
) or double quotation marks ("text"
). Single quotation marks are used for characters in Julia ('c'
). - String concatenation is done with
*
in Julia, not+
like in Python. Analogously, string repetition is done with^
, not*
. Implicit string concatenation of string literals like in Python (e.g.'ab' 'cd' == 'abcd'
) is not done in Julia. - Python Lists—flexible but slow—correspond to the Julia
Vector{Any}
type or more generallyVector{T}
whereT
is some non-concrete element type. “Fast” arrays like NumPy arrays that store elements in-place (i.e.,dtype
isnp.float64
,[('f1', np.uint64), ('f2', np.int32)]
, etc.) can be represented byArray{T}
whereT
is a concrete, immutable element type. This includes built-in types likeFloat64
,Int32
,Int64
but also more complex types likeTuple{UInt64,Float64}
and many user-defined types as well. - In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.
- Julia’s slice indexing includes the last element, unlike in Python.
a[2:3]
in Julia isa[1:3]
in Python. - Unlike Python, Julia allowsAbstractArrays with arbitrary indexes. Python’s special interpretation of negative indexing,
a[-1]
anda[-2]
, should be writtena[end]
anda[end-1]
in Julia. - Julia requires
end
for indexing until the last element.x[1:]
in Python is equivalent tox[2:end]
in Julia. - In Julia,
:
before any object creates aSymbol
or_quotes_an expression; so,x[:5]
is same asx[5]
. If you want to get the firstn
elements of an array, then use range indexing. - Julia’s range indexing has the format of
x[start:step:stop]
, whereas Python’s format isx[start:(stop+1):step]
. Hence,x[0:10:2]
in Python is equivalent tox[1:2:10]
in Julia. Similarly,x[::-1]
in Python, which refers to the reversed array, is equivalent tox[end:-1:1]
in Julia. - In Julia, ranges can be constructed independently as
start:step:stop
, the same syntax it uses in array-indexing. Therange
function is also supported. - In Julia, indexing a matrix with arrays like
X[[1,2], [1,3]]
refers to a sub-matrix that contains the intersections of the first and second rows with the first and third columns. In Python,X[[1,2], [1,3]]
refers to a vector that contains the values of cell[1,1]
and[2,3]
in the matrix.X[[1,2], [1,3]]
in Julia is equivalent withX[np.ix_([0,1],[0,2])]
in Python.X[[0,1], [0,2]]
in Python is equivalent withX[[CartesianIndex(1,1), CartesianIndex(2,3)]]
in Julia. - Julia has no line continuation syntax: if, at the end of a line, the input so far is a complete expression, it is considered done; otherwise the input continues. One way to force an expression to continue is to wrap it in parentheses.
- Julia arrays are column-major (Fortran-ordered) whereas NumPy arrays are row-major (C-ordered) by default. To get optimal performance when looping over arrays, the order of the loops should be reversed in Julia relative to NumPy (seerelevant section of Performance Tips).
- Julia’s updating operators (e.g.
+=
,-=
, …) are_not in-place_whereas NumPy’s are. This meansA = [1, 1]; B = A; B += [3, 3]
doesn’t change values inA
, it rather rebinds the nameB
to the result of the right-hand sideB = B + 3
, which is a new array. For in-place operation, useB .+= 3
(see alsodot operators), explicit loops, orInplaceOps.jl
. - Julia evaluates default values of function arguments every time the method is invoked, unlike in Python where the default values are evaluated only once when the function is defined. For example, the function
f(x=rand()) = x
returns a new random number every time it is invoked without argument. On the other hand, the functiong(x=[1,2]) = push!(x,3)
returns[1,2,3]
every time it is called asg()
. - In Julia, keyword arguments must be passed using keywords, unlike Python in which it is usually possible to pass them positionally. Attempting to pass a keyword argument positionally alters the method signature leading to a
MethodError
or calling of the wrong method. - In Julia
%
is the remainder operator, whereas in Python it is the modulus. - In Julia, the commonly used
Int
type corresponds to the machine integer type (Int32
orInt64
), unlike in Python, whereint
is an arbitrary length integer. This means in Julia theInt
type will overflow, such that2^64 == 0
. If you need larger values use another appropriate type, such asInt128
,BigInt
or a floating point type likeFloat64
. - The imaginary unit
sqrt(-1)
is represented in Julia asim
, notj
as in Python. - In Julia, the exponentiation operator is
^
, not**
as in Python. - Julia uses
nothing
of typeNothing
to represent a null value, whereas Python usesNone
of typeNoneType
. - In Julia, the standard operators over a matrix type are matrix operations, whereas, in Python, the standard operators are element-wise operations. When both
A
andB
are matrices,A * B
in Julia performs matrix multiplication, not element-wise multiplication as in Python.A * B
in Julia is equivalent withA @ B
in Python, whereasA * B
in Python is equivalent withA .* B
in Julia. - The adjoint operator
'
in Julia returns an adjoint of a vector (a lazy representation of row vector), whereas the transpose operator.T
over a vector in Python returns the original vector (non-op). - In Julia, a function may contain multiple concrete implementations (called_methods_), which are selected via multiple dispatch based on the types of all arguments to the call, as compared to functions in Python, which have a single implementation and no polymorphism (as opposed to Python method calls which use a different syntax and allows dispatch on the receiver of the method).
- There are no classes in Julia. Instead there are structures (mutable or immutable), containing data but no methods.
- Calling a method of a class instance in Python (
x = MyClass(*args); x.f(y)
) corresponds to a function call in Julia, e.g.x = MyType(args...); f(x, y)
. In general, multiple dispatch is more flexible and powerful than the Python class system. - Julia structures may have exactly one abstract supertype, whereas Python classes can inherit from one or more (abstract or concrete) superclasses.
- The logical Julia program structure (Packages and Modules) is independent of the file structure (
include
for additional files), whereas the Python code structure is defined by directories (Packages) and files (Modules). - The ternary operator
x > 0 ? 1 : -1
in Julia corresponds to a conditional expression in Python1 if x > 0 else -1
. - In Julia the
@
symbol refers to a macro, whereas in Python it refers to a decorator. - Exception handling in Julia is done using
try
—catch
—finally
, instead oftry
—except
—finally
. In contrast to Python, it is not recommended to use exception handling as part of the normal workflow in Julia (compared with Python, Julia is faster at ordinary control flow but slower at exception-catching). - In Julia loops are fast, there is no need to write “vectorized” code for performance reasons.
- Be careful with non-constant global variables in Julia, especially in tight loops. Since you can write close-to-metal code in Julia (unlike Python), the effect of globals can be drastic (seePerformance Tips).
- In Julia, rounding and truncation are explicit. Python’s
int(3.7)
should befloor(Int, 3.7)
orInt(floor(3.7))
and is distinguished fromround(Int, 3.7)
.floor(x)
andround(x)
on their own return an integer value of the same type asx
rather than always returningInt
. - In Julia, parsing is explicit. Python’s
float("3.7")
would beparse(Float64, "3.7")
in Julia. - In Python, the majority of values can be used in logical contexts (e.g.
if "a":
means the following block is executed, andif "":
means it is not). In Julia, you need explicit conversion toBool
(e.g.if "a"
throws an exception). If you want to test for a non-empty string in Julia, you would explicitly writeif !isempty("")
. Perhaps surprisingly, in Pythonif "False"
andbool("False")
both evaluate toTrue
(because"False"
is a non-empty string); in Julia,parse(Bool, "false")
returnsfalse
. - In Julia, a new local scope is introduced by most code blocks, including loops and
try
—catch
—finally
. Note that comprehensions (list, generator, etc.) introduce a new local scope both in Python and Julia, whereasif
blocks do not introduce a new local scope in both languages.
Noteworthy differences from Python
How are global variables handled in Julia compared to Python?
Noteworthy differences from Python
- Julia’s
for
,if
,while
, etc. blocks are terminated by theend
keyword. Indentation level is not significant as it is in Python. Unlike Python, Julia has nopass
keyword. - Strings are denoted by double quotation marks (
"text"
) in Julia (with three double quotation marks for multi-line strings), whereas in Python they can be denoted either by single ('text'
) or double quotation marks ("text"
). Single quotation marks are used for characters in Julia ('c'
). - String concatenation is done with
*
in Julia, not+
like in Python. Analogously, string repetition is done with^
, not*
. Implicit string concatenation of string literals like in Python (e.g.'ab' 'cd' == 'abcd'
) is not done in Julia. - Python Lists—flexible but slow—correspond to the Julia
Vector{Any}
type or more generallyVector{T}
whereT
is some non-concrete element type. “Fast” arrays like NumPy arrays that store elements in-place (i.e.,dtype
isnp.float64
,[('f1', np.uint64), ('f2', np.int32)]
, etc.) can be represented byArray{T}
whereT
is a concrete, immutable element type. This includes built-in types likeFloat64
,Int32
,Int64
but also more complex types likeTuple{UInt64,Float64}
and many user-defined types as well. - In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.
- Julia’s slice indexing includes the last element, unlike in Python.
a[2:3]
in Julia isa[1:3]
in Python. - Unlike Python, Julia allowsAbstractArrays with arbitrary indexes. Python’s special interpretation of negative indexing,
a[-1]
anda[-2]
, should be writtena[end]
anda[end-1]
in Julia. - Julia requires
end
for indexing until the last element.x[1:]
in Python is equivalent tox[2:end]
in Julia. - In Julia,
:
before any object creates aSymbol
or_quotes_an expression; so,x[:5]
is same asx[5]
. If you want to get the firstn
elements of an array, then use range indexing. - Julia’s range indexing has the format of
x[start:step:stop]
, whereas Python’s format isx[start:(stop+1):step]
. Hence,x[0:10:2]
in Python is equivalent tox[1:2:10]
in Julia. Similarly,x[::-1]
in Python, which refers to the reversed array, is equivalent tox[end:-1:1]
in Julia. - In Julia, ranges can be constructed independently as
start:step:stop
, the same syntax it uses in array-indexing. Therange
function is also supported. - In Julia, indexing a matrix with arrays like
X[[1,2], [1,3]]
refers to a sub-matrix that contains the intersections of the first and second rows with the first and third columns. In Python,X[[1,2], [1,3]]
refers to a vector that contains the values of cell[1,1]
and[2,3]
in the matrix.X[[1,2], [1,3]]
in Julia is equivalent withX[np.ix_([0,1],[0,2])]
in Python.X[[0,1], [0,2]]
in Python is equivalent withX[[CartesianIndex(1,1), CartesianIndex(2,3)]]
in Julia. - Julia has no line continuation syntax: if, at the end of a line, the input so far is a complete expression, it is considered done; otherwise the input continues. One way to force an expression to continue is to wrap it in parentheses.
- Julia arrays are column-major (Fortran-ordered) whereas NumPy arrays are row-major (C-ordered) by default. To get optimal performance when looping over arrays, the order of the loops should be reversed in Julia relative to NumPy (seerelevant section of Performance Tips).
- Julia’s updating operators (e.g.
+=
,-=
, …) are_not in-place_whereas NumPy’s are. This meansA = [1, 1]; B = A; B += [3, 3]
doesn’t change values inA
, it rather rebinds the nameB
to the result of the right-hand sideB = B + 3
, which is a new array. For in-place operation, useB .+= 3
(see alsodot operators), explicit loops, orInplaceOps.jl
. - Julia evaluates default values of function arguments every time the method is invoked, unlike in Python where the default values are evaluated only once when the function is defined. For example, the function
f(x=rand()) = x
returns a new random number every time it is invoked without argument. On the other hand, the functiong(x=[1,2]) = push!(x,3)
returns[1,2,3]
every time it is called asg()
. - In Julia, keyword arguments must be passed using keywords, unlike Python in which it is usually possible to pass them positionally. Attempting to pass a keyword argument positionally alters the method signature leading to a
MethodError
or calling of the wrong method. - In Julia
%
is the remainder operator, whereas in Python it is the modulus. - In Julia, the commonly used
Int
type corresponds to the machine integer type (Int32
orInt64
), unlike in Python, whereint
is an arbitrary length integer. This means in Julia theInt
type will overflow, such that2^64 == 0
. If you need larger values use another appropriate type, such asInt128
,BigInt
or a floating point type likeFloat64
. - The imaginary unit
sqrt(-1)
is represented in Julia asim
, notj
as in Python. - In Julia, the exponentiation operator is
^
, not**
as in Python. - Julia uses
nothing
of typeNothing
to represent a null value, whereas Python usesNone
of typeNoneType
. - In Julia, the standard operators over a matrix type are matrix operations, whereas, in Python, the standard operators are element-wise operations. When both
A
andB
are matrices,A * B
in Julia performs matrix multiplication, not element-wise multiplication as in Python.A * B
in Julia is equivalent withA @ B
in Python, whereasA * B
in Python is equivalent withA .* B
in Julia. - The adjoint operator
'
in Julia returns an adjoint of a vector (a lazy representation of row vector), whereas the transpose operator.T
over a vector in Python returns the original vector (non-op). - In Julia, a function may contain multiple concrete implementations (called_methods_), which are selected via multiple dispatch based on the types of all arguments to the call, as compared to functions in Python, which have a single implementation and no polymorphism (as opposed to Python method calls which use a different syntax and allows dispatch on the receiver of the method).
- There are no classes in Julia. Instead there are structures (mutable or immutable), containing data but no methods.
- Calling a method of a class instance in Python (
x = MyClass(*args); x.f(y)
) corresponds to a function call in Julia, e.g.x = MyType(args...); f(x, y)
. In general, multiple dispatch is more flexible and powerful than the Python class system. - Julia structures may have exactly one abstract supertype, whereas Python classes can inherit from one or more (abstract or concrete) superclasses.
- The logical Julia program structure (Packages and Modules) is independent of the file structure (
include
for additional files), whereas the Python code structure is defined by directories (Packages) and files (Modules). - The ternary operator
x > 0 ? 1 : -1
in Julia corresponds to a conditional expression in Python1 if x > 0 else -1
. - In Julia the
@
symbol refers to a macro, whereas in Python it refers to a decorator. - Exception handling in Julia is done using
try
—catch
—finally
, instead oftry
—except
—finally
. In contrast to Python, it is not recommended to use exception handling as part of the normal workflow in Julia (compared with Python, Julia is faster at ordinary control flow but slower at exception-catching). - In Julia loops are fast, there is no need to write “vectorized” code for performance reasons.
- Be careful with non-constant global variables in Julia, especially in tight loops. Since you can write close-to-metal code in Julia (unlike Python), the effect of globals can be drastic (seePerformance Tips).
- In Julia, rounding and truncation are explicit. Python’s
int(3.7)
should befloor(Int, 3.7)
orInt(floor(3.7))
and is distinguished fromround(Int, 3.7)
.floor(x)
andround(x)
on their own return an integer value of the same type asx
rather than always returningInt
. - In Julia, parsing is explicit. Python’s
float("3.7")
would beparse(Float64, "3.7")
in Julia. - In Python, the majority of values can be used in logical contexts (e.g.
if "a":
means the following block is executed, andif "":
means it is not). In Julia, you need explicit conversion toBool
(e.g.if "a"
throws an exception). If you want to test for a non-empty string in Julia, you would explicitly writeif !isempty("")
. Perhaps surprisingly, in Pythonif "False"
andbool("False")
both evaluate toTrue
(because"False"
is a non-empty string); in Julia,parse(Bool, "false")
returnsfalse
. - In Julia, a new local scope is introduced by most code blocks, including loops and
try
—catch
—finally
. Note that comprehensions (list, generator, etc.) introduce a new local scope both in Python and Julia, whereasif
blocks do not introduce a new local scope in both languages.
Noteworthy differences from Python
How do Julia and Python differ with rounding and truncation?
Noteworthy differences from Python
- Julia’s
for
,if
,while
, etc. blocks are terminated by theend
keyword. Indentation level is not significant as it is in Python. Unlike Python, Julia has nopass
keyword. - Strings are denoted by double quotation marks (
"text"
) in Julia (with three double quotation marks for multi-line strings), whereas in Python they can be denoted either by single ('text'
) or double quotation marks ("text"
). Single quotation marks are used for characters in Julia ('c'
). - String concatenation is done with
*
in Julia, not+
like in Python. Analogously, string repetition is done with^
, not*
. Implicit string concatenation of string literals like in Python (e.g.'ab' 'cd' == 'abcd'
) is not done in Julia. - Python Lists—flexible but slow—correspond to the Julia
Vector{Any}
type or more generallyVector{T}
whereT
is some non-concrete element type. “Fast” arrays like NumPy arrays that store elements in-place (i.e.,dtype
isnp.float64
,[('f1', np.uint64), ('f2', np.int32)]
, etc.) can be represented byArray{T}
whereT
is a concrete, immutable element type. This includes built-in types likeFloat64
,Int32
,Int64
but also more complex types likeTuple{UInt64,Float64}
and many user-defined types as well. - In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.
- Julia’s slice indexing includes the last element, unlike in Python.
a[2:3]
in Julia isa[1:3]
in Python. - Unlike Python, Julia allowsAbstractArrays with arbitrary indexes. Python’s special interpretation of negative indexing,
a[-1]
anda[-2]
, should be writtena[end]
anda[end-1]
in Julia. - Julia requires
end
for indexing until the last element.x[1:]
in Python is equivalent tox[2:end]
in Julia. - In Julia,
:
before any object creates aSymbol
or_quotes_an expression; so,x[:5]
is same asx[5]
. If you want to get the firstn
elements of an array, then use range indexing. - Julia’s range indexing has the format of
x[start:step:stop]
, whereas Python’s format isx[start:(stop+1):step]
. Hence,x[0:10:2]
in Python is equivalent tox[1:2:10]
in Julia. Similarly,x[::-1]
in Python, which refers to the reversed array, is equivalent tox[end:-1:1]
in Julia. - In Julia, ranges can be constructed independently as
start:step:stop
, the same syntax it uses in array-indexing. Therange
function is also supported. - In Julia, indexing a matrix with arrays like
X[[1,2], [1,3]]
refers to a sub-matrix that contains the intersections of the first and second rows with the first and third columns. In Python,X[[1,2], [1,3]]
refers to a vector that contains the values of cell[1,1]
and[2,3]
in the matrix.X[[1,2], [1,3]]
in Julia is equivalent withX[np.ix_([0,1],[0,2])]
in Python.X[[0,1], [0,2]]
in Python is equivalent withX[[CartesianIndex(1,1), CartesianIndex(2,3)]]
in Julia. - Julia has no line continuation syntax: if, at the end of a line, the input so far is a complete expression, it is considered done; otherwise the input continues. One way to force an expression to continue is to wrap it in parentheses.
- Julia arrays are column-major (Fortran-ordered) whereas NumPy arrays are row-major (C-ordered) by default. To get optimal performance when looping over arrays, the order of the loops should be reversed in Julia relative to NumPy (seerelevant section of Performance Tips).
- Julia’s updating operators (e.g.
+=
,-=
, …) are_not in-place_whereas NumPy’s are. This meansA = [1, 1]; B = A; B += [3, 3]
doesn’t change values inA
, it rather rebinds the nameB
to the result of the right-hand sideB = B + 3
, which is a new array. For in-place operation, useB .+= 3
(see alsodot operators), explicit loops, orInplaceOps.jl
. - Julia evaluates default values of function arguments every time the method is invoked, unlike in Python where the default values are evaluated only once when the function is defined. For example, the function
f(x=rand()) = x
returns a new random number every time it is invoked without argument. On the other hand, the functiong(x=[1,2]) = push!(x,3)
returns[1,2,3]
every time it is called asg()
. - In Julia, keyword arguments must be passed using keywords, unlike Python in which it is usually possible to pass them positionally. Attempting to pass a keyword argument positionally alters the method signature leading to a
MethodError
or calling of the wrong method. - In Julia
%
is the remainder operator, whereas in Python it is the modulus. - In Julia, the commonly used
Int
type corresponds to the machine integer type (Int32
orInt64
), unlike in Python, whereint
is an arbitrary length integer. This means in Julia theInt
type will overflow, such that2^64 == 0
. If you need larger values use another appropriate type, such asInt128
,BigInt
or a floating point type likeFloat64
. - The imaginary unit
sqrt(-1)
is represented in Julia asim
, notj
as in Python. - In Julia, the exponentiation operator is
^
, not**
as in Python. - Julia uses
nothing
of typeNothing
to represent a null value, whereas Python usesNone
of typeNoneType
. - In Julia, the standard operators over a matrix type are matrix operations, whereas, in Python, the standard operators are element-wise operations. When both
A
andB
are matrices,A * B
in Julia performs matrix multiplication, not element-wise multiplication as in Python.A * B
in Julia is equivalent withA @ B
in Python, whereasA * B
in Python is equivalent withA .* B
in Julia. - The adjoint operator
'
in Julia returns an adjoint of a vector (a lazy representation of row vector), whereas the transpose operator.T
over a vector in Python returns the original vector (non-op). - In Julia, a function may contain multiple concrete implementations (called_methods_), which are selected via multiple dispatch based on the types of all arguments to the call, as compared to functions in Python, which have a single implementation and no polymorphism (as opposed to Python method calls which use a different syntax and allows dispatch on the receiver of the method).
- There are no classes in Julia. Instead there are structures (mutable or immutable), containing data but no methods.
- Calling a method of a class instance in Python (
x = MyClass(*args); x.f(y)
) corresponds to a function call in Julia, e.g.x = MyType(args...); f(x, y)
. In general, multiple dispatch is more flexible and powerful than the Python class system. - Julia structures may have exactly one abstract supertype, whereas Python classes can inherit from one or more (abstract or concrete) superclasses.
- The logical Julia program structure (Packages and Modules) is independent of the file structure (
include
for additional files), whereas the Python code structure is defined by directories (Packages) and files (Modules). - The ternary operator
x > 0 ? 1 : -1
in Julia corresponds to a conditional expression in Python1 if x > 0 else -1
. - In Julia the
@
symbol refers to a macro, whereas in Python it refers to a decorator. - Exception handling in Julia is done using
try
—catch
—finally
, instead oftry
—except
—finally
. In contrast to Python, it is not recommended to use exception handling as part of the normal workflow in Julia (compared with Python, Julia is faster at ordinary control flow but slower at exception-catching). - In Julia loops are fast, there is no need to write “vectorized” code for performance reasons.
- Be careful with non-constant global variables in Julia, especially in tight loops. Since you can write close-to-metal code in Julia (unlike Python), the effect of globals can be drastic (seePerformance Tips).
- In Julia, rounding and truncation are explicit. Python’s
int(3.7)
should befloor(Int, 3.7)
orInt(floor(3.7))
and is distinguished fromround(Int, 3.7)
.floor(x)
andround(x)
on their own return an integer value of the same type asx
rather than always returningInt
. - In Julia, parsing is explicit. Python’s
float("3.7")
would beparse(Float64, "3.7")
in Julia. - In Python, the majority of values can be used in logical contexts (e.g.
if "a":
means the following block is executed, andif "":
means it is not). In Julia, you need explicit conversion toBool
(e.g.if "a"
throws an exception). If you want to test for a non-empty string in Julia, you would explicitly writeif !isempty("")
. Perhaps surprisingly, in Pythonif "False"
andbool("False")
both evaluate toTrue
(because"False"
is a non-empty string); in Julia,parse(Bool, "false")
returnsfalse
. - In Julia, a new local scope is introduced by most code blocks, including loops and
try
—catch
—finally
. Note that comprehensions (list, generator, etc.) introduce a new local scope both in Python and Julia, whereasif
blocks do not introduce a new local scope in both languages.