Julia, Software Development

How To Create Array Literals In Julia

Photo by Elina Krima from Pexels

This post is about how to create array literals in Julia. When we write out array values, we create array literals. Julia can readily interpret these array literals. There are other ways to create arrays in Julia, but we will stick with array literals on this post.

Create Empty Literal Arrays

An empty array has a type of Array{Any, 1}, which means it is a one-dimensional array that can have values of any type. Yes, they can store values of different types.

We can push any value to the array, as follows.

We can also create an empty array of a specific data type. As a result, the array can also accept values of that type.

When we run the codes to add values of various types to the array, we get the following error.

Create Two-dimensional Arrays

We can also create two-dimensional array literals. Consider the following codes. Note the semi-colon and spaces between the values.

Create Arrays of Arrays Literals

Arrays of arrays are different from multi-dimensional arrays. For instance, consider the following codes. They show how to create an array of an array literal in Julia.

Notice how we use the square brackets now. We are handling more square brackets both in the array definition and in accessing each value in the array. Each pair represents an array. We can also break down the array into individual collections.

When we use Array{Array{String,1}, 1} to specify the type of the array explicitly, we get an error. Consider the following codes.

These codes result in an error.

To fix the error, we use the following array type.

Create Array Literals With Default Values

We can also create arrays with default values using comprehensions. Comprehensions do not create array literals, but they provide a convenient means to create arrays with default values. Consider the following codes.

We tested the codes using Julia 1.4.0.

You Might Also Like

Leave a Reply

Your email address will not be published. Required fields are marked *