Home Â» Julia Â» Convert Array to Tuple in Julia

# Convert Array to Tuple in Julia

In Julia, arrays and tuples are two different types of data structures that are used to store and manipulate data. An array is a collection of data elements that are all of the same types and are stored in contiguous memory locations. Arrays are typically used to store large amounts of data that need to be processed efficiently, such as in scientific or numerical computing. Tuples, on the other hand, are collections of data elements that can be of different types. Unlike arrays, tuples are not stored in contiguous memory locations and can have a variable number of elements. Tuples are typically used to store a small number of related values that need to be accessed quickly, such as in a record or a coordinate system. To convert an array to a tuple in Julia, you can use the `tuple` function. Below are the examples:

## Convert Array to Tuple in Julia Examples

```# Define the array
arr = [1, 2, 3, 4, 5]

# Convert the array to a tuple
tup = tuple(arr)

# Print the tuple
println(tup)```

This code will create a tuple containing the same values as the array. The output will look like this:

`(1, 2, 3, 4, 5)`

You can also convert a multi-dimensional array to a tuple. For example, the following code will convert a 2D array to a tuple of tuples:

```# Define the 2D array
arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

# Convert the array to a tuple of tuples
tup = tuple(map(tuple, arr))

# Print the tuple
println(tup)```

This code will create a tuple containing three tuples, each containing the values from the corresponding row in the array. The output will look like this:

`((1, 2, 3), (4, 5, 6), (7, 8, 9))`

You can also use the `collect` function to convert the array to a tuple. The `collect` function will convert an array-like object to a tuple or array, depending on the type of the object. Here is an example of how to use the `collect` function to convert an array to a tuple:

```# Define the array
arr = [1, 2, 3, 4, 5]

# Convert the array to a tuple using the collect function
tup = collect(arr)

# Print the tuple
println(tup)```

This code will create a tuple containing the same values as the array. The output will look like this:

`(1, 2, 3, 4, 5)`

You can also use the `collect` function to convert a multi-dimensional array to a tuple. For example, the following code will convert a 2D array to a tuple of tuples:

```# Define the 2D array
arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

# Convert the array to a tuple of tuples using the collect function
tup = collect(map(collect, arr))

# Print the tuple
println(tup)```

This code will create a tuple containing three tuples, each containing the values from the corresponding row in the array. The output will look like this:

`((1, 2, 3), (4, 5, 6), (7, 8, 9))`

### Related:

1. Convert Array to DataFrame in Julia