Julia 101

MUHAMMAD SALMAN KABIR
2 min readApr 4

--

Lesson 4: Tuples

Tuples in Julia programming language

One of the most useful data structures in Julia is the tuple, which is an ordered collection of elements that can be of any data type. Tuples are immutable, which means that once they are created, their values cannot be changed. In this post, we will explore how to work with tuples in Julia.

Creating Tuples:

Creating a tuple in Julia is simple. We can create a tuple by enclosing a sequence of elements in parentheses, separated by commas. For example, the following code creates a tuple with three elements:

my_tuple = ("City",1,2,"Country",3)

We can also create a tuple using the tuple() function. For example:

my_tuple = tuple("City",1,2,"Country",3)

Accessing Elements in Tuples:

We can access individual elements in a tuple by using indexing. In Julia, indexing starts from 1, not 0 (reminder). To access the first element in a tuple, we can use the syntax my_tuple[1]. For example, to access the first element of the tuple created above, we can use:

my_tuple[1] # Returns City

We can access the other elements in the tuple by changing the index. For example, to access the second element of the tuple, we can use:

my_tuple[2] # Returns 1

Iterating over Tuples:

We can iterate over a tuple using a for loop (stay tune for a detail lesson on loops). For example:

my_tuple = ("City",1,2,"Country",3)

for element in my_tuple
println(element)
end

This code will print each element of the tuple on a separate line.

Tuple Unpacking:

We can also use tuple unpacking to assign the elements of a tuple to variables. For example:

my_tuple = ("City",1,2,"Country",3)
a, b, c = my_tuple

In this code, the values of the elements in my_tuple are assigned to the variables a, b, and c. Now, a is equal to 1, b is equal to 2, and c is equal to 3.

Returning Multiple Values:

One of the most common use cases for tuples in Julia is to return multiple values from a function. For example:

function my_function(x, y)
return x + y, x - y
end

a, b = my_function(3, 2)

In this code, the my_function function returns a tuple with two elements: the sum of x and y, and the difference between x and y. The values in this tuple are then assigned to the variables a and b.

Length of Tuples:

We can calculate the length of a tuple in Julia using the length() function. For example:

my_tuple = ("City",1,2,"Country",3)
length(my_tuple) # Returns 5

Reversing Elements in Tuples:

We can reverse the order of elements in a tuple using the reverse() function. For example:

my_tuple = ("City",1,2,"Country",3)
reverse(my_tuple) # Returns (3,"Country",2,1,"City")

--

--

MUHAMMAD SALMAN KABIR

Electrical Engineer | Signal Processing & Machine Learning Enthusiast