# Comparing Julia, Python, and R

## Introduction

This section will compare Julia, Python, and R syntax and methods for achieving similar functionality.

## Performance Metrics

<figure><img src="https://lh7-us.googleusercontent.com/GXLA9jNYKrv7Lni1sqVAZY5aUO-cmWct40SGIKzml53dgAeE-rbq00jVDCIIvIYxCxHVKbT2qjksYpy1fUvjgStLc3UQkAivG_ZEW7G4dB8R3CKhP3C6pWE6N5ctZCUlBx9Wsjri8lClGB0HzE7UjYs" alt=""><figcaption></figcaption></figure>

## Basic Syntax <a href="#basic_syntax" id="basic_syntax"></a>

### REPL <a href="#repl" id="repl"></a>

Much like Julia, Python provides a REPL (read-eval-print loop) to run code:

```
$ julia
$ python
```

When using Python, it is important to note that syntax and packages may vary depending on the version you have installed. Thus as with the Julia REPL, you can check your version of Python by adding the `--version` argument to the above command.

### Setting Variables <a href="#setting_variables" id="setting_variables"></a>

The syntax for setting variables is exactly the same for each language:

Python:

```python
= 1
```

Julia

```julia
= 1
```

Python provides the `type(x)` function in order to find the type of a variable `x`.

### Types <a href="#types" id="types"></a>

The following table shows the some basic types in Julia and Python:

| Description |  Julia | Python |
| ----------: | -----: | -----: |
|     Integer |    Int |    int |
|       Float |  Float |  float |
|      String | String |    str |

### Logical and Equality Operators <a href="#logical_and_equality_operators" id="logical_and_equality_operators"></a>

The following table shows the logical operators in Julia and Python:

|         Description |                Julia |               Python |
| ------------------: | -------------------: | -------------------: |
|         Logical And |                   && |                  and |
|          Logical Or |                 \|\| |                   or |
|         Logical Not |                    ! |                  not |
| Equality/Inequality | == / < / > / <= / >= | == / < / > / <= / >= |
|           Not Equal |                   != |                   != |

### If Statements <a href="#if_statements" id="if_statements"></a>

Python:

```python
if (boolean expression):
     Code to run
```

Julia:

```julia
if (boolean expression)
    Code to run
end
```

One of the key syntactical features of Python is how it uses whitespace. Instead of adding the `end` keyword to denote the end of an if statement, in Python, only code that is tabbed under the if statement will run.

### While Loops <a href="#while_loops" id="while_loops"></a>

Python:

```python
while (boolean expression):
    Code to run
```

Julia:

```julia
while (boolean expression)
    Code to run
end
```

Similar to if statements, in Python the code that needs to be run inside the while loop should be tabbed.

### For Loops <a href="#for_loops" id="for_loops"></a>

Python:

```python
for element in range:
    Code to run
```

Julia:

```julia
for element = range
    Code to run
end
```

### Functions <a href="#functions" id="functions"></a>

A simple example of a function that returns the sum of two integers can be seen below.

Python:

```python
def function_name(x,y):
    return x + y
```

Julia:

```julia
function function_name(x,y)
    return x + y
end
```

### Commenting <a href="#commenting" id="commenting"></a>

Python:

```python
# The hash symbol denotes a single line comment
‘’’
Three single quotes denotes
a multiline comment.
‘’’
```

Julia:

```julia
# The hash symbol denotes a single line comment
#=
The hash symbol with an equals sign is
a multiline comment.
=#
```

## Data Structures <a href="#data_structures" id="data_structures"></a>

### Arrays <a href="#arrays" id="arrays"></a>

#### **Creating Arrays**

Python and Julia have similar syntax to create an Array. In Python, arrays are called lists. While in Julia we can define Array types, Python arrays cannot have type constraints without additional packages.

The syntax to create an array in both languages is as follows:

```python
array = []
```

#### **Indexing in Arrays**

Unlike in Julia, Python indexes at 0 rather than 1. Thus in order to access the first element in an array we would write `array[0]`, while in Julia it would be `array[1]`. To access the last index in an array, Python provides negative indexing. Thus in Python we would use `array[-1]`, where in Julia we would use `array[end]`. Python's negative indexing may also be useful for indexing an array in reverse. If we want to access for example the second-to-last element in a Python array we can use `array[-2]`.

Python, much like Julia, also offers array slicing in order to retrieve subsets of arrays. The syntax is similar for both languages for array slicing: `array[(start index):(end index)]`, where start index and end index are the indices where you would like your array slice to start and end. It must be noted that Python's end index, uinlike in Julia, is not inclusive. In other words if we wanted to access the elements from the first to third indices we would need to write `array[0:3]` in Python, where the fourth element at `array[3]` will not be included in the subset of the array.

In Python the syntax also allows us to omit indices that are implied: if we want to get the slice of the array that starts at the second index and ends at the last index we can write `array[1:]`, where in Julia we would write `array[2:end]`. We can omit the ending index after the colon, as it implied when left out that we want to include the rest of the array in our slice. Similarly, if we wanted to have a slice that starts at the beginning of the array and lasts at the second to last element we would use `array[:-1]`, where in Julia we would use `array[1:length(a)-1]`.

#### **Appending to Arrays**

Python:

```python
array.append(element)
```

Julia:

```julia
append!(array,element)
```

#### **Array Length**

Python:

```python
len(array)
```

Julia:

```julia
length(array)
```

#### **Array/List Comprehension**

Both languages provide syntax that shortens iteratively adding elements to an array:

Python:

```python
[expression for element in iterable]
```

Julia:

```julia
[expression for element = iterable]
```

For example if we wanted to create an array with the first 10 squares we would write the following:

Python:

```python
[x ** 2 for x in range(1,11)]
```

Julia:

```julia
[x ^ 2 for x = 1:10]
```

The example above would yield `[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]` in both languages.

#### **Python Documentation**

Documentation on Python lists can be found [here](https://docs.python.org/3/tutorial/datastructures.html) .

### Sets <a href="#sets" id="sets"></a>

#### **Creating Sets**

Python:

```python
s = set()
```

Julia:

```julia
s = Set()
```

#### **Adding/Removing Elements**

Python:

```python
s.add(element)
s.remove(element)
```

Julia:

```julia
push!(s,element)
delete!(s,element)
```

#### **Set Operations**

Python:

```python
a = b = set()
a.add(1)
b.add(2)
```

* Union: `a | b` and outputs: `set([1,2])`
* Intersection `a & b` and outputs: `set([])`

Julia:

```julia
a = b = Set()
push!(a,1)
push!(b,2)
```

* Union: `union(a,b)` and outputs: `set(Any[1,2])`
* Intersection `intersect(a,b)` and outputs: `set(Any[])`

#### **Python Documentation**

More set operations in Python can be found in the official Python set docummentation [page](https://docs.python.org/3/library/stdtypes.html#set) .

### Dictionaries <a href="#dictionaries" id="dictionaries"></a>

#### **Creating a Dictionary**

Python: `d = {}` or `d = dict()`

Julia:

```julia
d = Dict()
```

#### **Accessing Dictionary**

Python:

```python
d[key] = value
```

Julia:

```julia
d[key] = value
```

#### **Iterating Through Key-Value Pairs:**

The below example prints all key value pairs in a dictionary `d`.

Python:

```python
for key, value in d.items():
    print(key,value)
```

Julia:

```julia
for (key, value) in d:
    print(key,value)
end
```

#### **Python Documentation**

Python official [documentation](https://docs.python.org/3/library/stdtypes.html#mapping-types-dict) on dictionaries further outlines the language's features.

### DataFrames <a href="#dataframes" id="dataframes"></a>

#### **Importing Libraries**

Both Python and Julia support the use of DataFrames through external libraries and hence must be imported. Python:

```python
import pandas as pd
```

Julia:

```julia
using DataFrames
```

#### **Creating a DataFrame**

Python:

```python
data = {
            'A': [element_1, element_2, ...],
            'B': [element_1, element_2, ...],
            ...
        }

df = pd.DataFrame(data)
```

Julia:

```julia
df = DataFrame(A = [element_1, element_2, ...], B = [element_1, element_2, ...])
```

#### **Accessing a Column**

Python and Julia: `df.A` or `df["A"]`

#### **pandas Documentation**

The full pandas documentation is very extensive and should have any features that we could find in DataFrames.jl. The documentation can be found [here](https://pandas.pydata.org/docs/user_guide/index.html) .

## Miscellaneous Tasks <a href="#miscellaneous_tasks" id="miscellaneous_tasks"></a>

### Reading a CSV file as a DataFrame <a href="#reading_a_csv_file_as_a_dataframe" id="reading_a_csv_file_as_a_dataframe"></a>

Python:

```python
import pandas as pd 
df = pd.read_csv([your filename])
```

Jullia:

```julia
using CSV
df = CSV.read([your filename])
```

### Installing Packages <a href="#installing_packages" id="installing_packages"></a>

Python:

```
$ pip install [package name]
```

Julia:

```julia
$julia
$julia>
```

Once in the Julia REPL you can type the close bracket symbol `]`, which will take you the package environment.

```
(v1.0) pkg> add [package name]
```

We can install any package from the package environment by replacing the package name with the wanted package.

### List of Useful Packages <a href="#list_of_useful_packages" id="list_of_useful_packages"></a>

Below are some useful packages for plotting, data processing, and various statistical learning packages. The links are provided for each of their documentation page.

* Plotting
  * [matplotlib](https://matplotlib.org/) is a highly configurable plotting package with great documentation.
  * [seaborn](https://seaborn.pydata.org/) is built on top of matplotlib and has graphs that look great out of the box without too much styling on the user's part.
* Data
  * [pandas](https://pandas.pydata.org/) is the Python equivalent of DataFrames in Julia.
  * [numpy](https://numpy.org/) expands features of arrays in pythons to allow for matrix operations. Much of these features are in vanilla Julia.
* Machine Learning and Stats
  * [scikit-learn](https://scikit-learn.org/stable/) is a robust package with a plethora of machine learning and statistical techniques.
  * [statsmodels](https://www.statsmodels.org/stable/index.html) is a package which is more geared towards statistical techniques and provides more metrics on how your model is performing.
* Deep Learning
  * [tensorflow](https://www.tensorflow.org/) is a complex and highly configurable deep learning platform created by Google.
  * [pytorch](https://pytorch.org/) similarly is a great deep learning platform created by Facebook.
  * [keras](https://keras.io/) is a high-level wrapper over other deep learning libraries to make deep learning more accesible.
* Text Processing and Natural Language Processing
  * [nltk](https://www.nltk.org/) is a package for text processing.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.bcbi.brown.edu/codiac-for-health/computing/comparing-julia-python-and-r.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
