print and println@printftry-catch for Exception HandlingfinallyJulia offers versatile collection types: Arrays, Tuples, Dictionaries, and Sets, along with concise syntax for their creation using comprehensions. Practice creating, manipulating, and utilizing these collections for various data management tasks through the following exercises. Typing these examples into your Julia REPL or a script file is encouraged to see them in action.
Arrays are ordered, mutable collections, making them ideal for lists of items that may need to be changed or extended.
1. Creating and Initializing Arrays
Julia offers several ways to create arrays. Let's try a few:
# An empty array, specifically for integers
empty_int_array = Int[]
println("Empty Integer Array: ", empty_int_array)
# An array with initial values; Julia infers the type
numbers = [10, 20, 30, 40, 50]
println("Numbers Array: ", numbers)
println("Type of numbers array: ", typeof(numbers)) # Shows Array{Int64, 1}
# An array of a specific type (Float64) with initial values
float_numbers = Float64[1.5, 2.5, 3.5]
println("Floating-Point Numbers Array: ", float_numbers)
# An array that can hold values of any type
mixed_array = [1, "hello Julia", 3.14, true]
println("Mixed Type Array: ", mixed_array)
println("Type of mixed_array: ", typeof(mixed_array)) # Shows Array{Any, 1}
# Using functions to create pre-filled arrays
zeros_array = zeros(Int8, 3) # Creates an array of three Int8 zeros: [0, 0, 0]
println("Zeros Array (Int8): ", zeros_array)
ones_array = ones(Float32, 2, 3) # Creates a 2x3 matrix of Float32 ones
println("Ones Array (2x3 Float32):")
display(ones_array) # `display` is often better for multi-dimensional arrays
2. Accessing and Modifying Elements
Remember, Julia uses 1-based indexing for arrays.
primes = [2, 3, 5, 7, 11, 13]
# Access the first element
first_prime = primes[1]
println("First prime: ", first_prime) # Output: 2
# Access the third element
third_prime = primes[3]
println("Third prime: ", third_prime) # Output: 5
# Access the last element using `end`
last_prime = primes[end]
println("Last prime: ", last_prime) # Output: 13
# Modify an element
println("Original primes: ", primes)
primes[3] = 99 # Let's change the third element
println("Modified primes (element 3 changed): ", primes)
primes[3] = 5 # Change it back
println("Corrected primes: ", primes)
3. Common Array Operations
Arrays come with many useful functions for manipulation. Functions ending with ! conventionally modify the array in-place.
inventory = ["apples", "bananas"]
println("Initial inventory: ", inventory)
# Add an element to the end of the array
push!(inventory, "oranges")
println("After push! 'oranges': ", inventory)
# Remove an element from the end and get its value
last_item = pop!(inventory)
println("Removed item (pop!): ", last_item)
println("Inventory after pop!: ", inventory)
# Add an element to the beginning of the array
pushfirst!(inventory, "strawberries")
println("After pushfirst! 'strawberries': ", inventory)
# Remove an element from the beginning and get its value
first_item = popfirst!(inventory)
println("Removed item (popfirst!): ", first_item)
println("Inventory after popfirst!: ", inventory)
# Get the number of elements in the array
println("Number of items in inventory: ", length(inventory))
# Sort an array (in-place modification)
unsorted_scores = [88, 75, 92, 60, 95]
println("Unsorted scores: ", unsorted_scores)
sort!(unsorted_scores)
println("Sorted scores: ", unsorted_scores)
# Append elements from another array (modifies the first array)
more_fruits = ["grapes", "mangoes"]
append!(inventory, more_fruits) # 'inventory' is modified
println("Inventory after append!: ", inventory)
# To combine arrays without modifying originals, use `vcat`
list_a = [10, 20]
list_b = [30, 40]
combined_list = vcat(list_a, list_b)
println("List A: ", list_a) # Remains [10, 20]
println("List B: ", list_b) # Remains [30, 40]
println("Combined list (new array): ", combined_list)
Tuples are ordered, immutable sequences. Their fixed nature makes them suitable for representing data whose structure and content should not change after creation, such as coordinates or fixed records.
1. Creating Tuples
# A tuple representing a 2D point
point_2d = (10, 20)
println("2D Point: ", point_2d)
# A tuple for RGB color values
red_color = (255, 0, 0)
println("Red color (RGB): ", red_color)
# A tuple with mixed data types
record = ("John Doe", 34, "New York")
println("Record: ", record)
# Accessing elements (1-based indexing, just like arrays)
name = record[1]
age = record[2]
city = record[3]
println("$name, aged $age, lives in $city.")
# Tuple unpacking for convenient assignment
x, y = point_2d
println("x-coordinate: $x, y-coordinate: $y")
2. Demonstrating Immutability
Attempting to change an element in a tuple will result in an error, highlighting their immutable property.
fixed_settings = (true, "fast_mode", 1024)
println("Fixed settings: ", fixed_settings)
# Try to change the first element:
# fixed_settings[1] = false # This line will cause an error if uncommented
# ERROR: MethodError: no method matching setindex!(::Tuple{Bool, String, Int64}, ::Bool, ::Int64)
This behavior is by design. If you need a collection that can be modified, an Array is the appropriate choice.
Dictionaries store data as key-value pairs, offering efficient data retrieval if you know the key. Keys must be unique.
1. Creating and Populating Dictionaries
# Creating an empty dictionary: Method 1
city_populations = Dict{String, Int}()
# Adding key-value pairs
city_populations["New York"] = 8_400_000 # Underscores in numbers are for readability
city_populations["Los Angeles"] = 3_900_000
city_populations["Chicago"] = 2_700_000
println("City Populations: ", city_populations)
# Creating a dictionary with initial pairs: Method 2
element_symbols = Dict("H" => "Hydrogen", "O" => "Oxygen", "C" => "Carbon")
println("Element Symbols: ", element_symbols)
2. Accessing, Modifying, and Managing Entries
# Accessing a value using its key
oxygen_name = element_symbols["O"]
println("Symbol 'O' stands for: ", oxygen_name)
# Modifying an existing value
println("Population of Chicago: ", city_populations["Chicago"])
city_populations["Chicago"] = 2_750_000 # Update population
println("Updated population of Chicago: ", city_populations["Chicago"])
# Checking if a key exists
has_helium = haskey(element_symbols, "He")
println("Does 'He' exist as a key? ", has_helium) # Output: false
has_carbon = haskey(element_symbols, "C")
println("Does 'C' exist as a key? ", has_carbon) # Output: true
# Getting a value with `get`, providing a default if the key is not found
helium_name = get(element_symbols, "He", "Symbol not found")
println("Name for 'He': ", helium_name)
carbon_name_get = get(element_symbols, "C", "Symbol not found")
println("Name for 'C' (using get): ", carbon_name_get)
# Removing a key-value pair
delete!(element_symbols, "H")
println("Element Symbols after deleting 'H': ", element_symbols)
3. Iterating Over Dictionaries
You can iterate through a dictionary's keys, its values, or its key-value pairs.
fruit_prices = Dict("apple" => 0.50, "banana" => 0.25, "orange" => 0.75)
println("\nAvailable Fruits (Keys):")
for fruit in keys(fruit_prices)
println(fruit)
end
println("\nFruit Prices (Values):")
for price in values(fruit_prices)
println(price)
end
println("\nComplete Price List (Key-Value Pairs):")
for (fruit, price) in fruit_prices
println("$fruit costs \$$price")
end
Let's visualize the fruit prices.
A bar chart displaying the price per unit for different fruits.
Sets are unordered collections of unique elements. They are particularly useful for operations like checking for membership, removing duplicates from a list, and performing standard set-theoretic operations (union, intersection, difference).
1. Creating Sets and Adding Elements
# Creating an empty set, specifying the element type
unique_tags = Set{String}()
# Adding elements to the set
push!(unique_tags, "julia")
push!(unique_tags, "programming")
push!(unique_tags, "data science")
push!(unique_tags, "julia") # Adding "julia" again has no effect as elements must be unique
println("Unique Tags: ", unique_tags) # Order of elements is not guaranteed
# Creating a set with initial elements
numbers_set = Set([1, 2, 2, 3, 4, 4, 4, 5])
println("Numbers Set (duplicates removed): ", numbers_set) # Output: Set([5, 2, 3, 1, 4]) or similar
2. Set Operations
Let's explore common set operations.
set_europe = Set(["France", "Germany", "Spain"])
set_g7 = Set(["USA", "Canada", "France", "Germany", "UK", "Italy", "Japan"])
# Union: All unique countries from both sets
union_countries = union(set_europe, set_g7)
println("Union (Europe or G7): ", union_countries)
# Intersection: Countries that are in both Europe AND G7
intersection_countries = intersect(set_europe, set_g7)
println("Intersection (European G7 members): ", intersection_countries)
# Difference: Countries in set_europe but NOT in set_g7
europe_not_g7 = setdiff(set_europe, set_g7)
println("Difference (European countries not in G7): ", europe_not_g7)
# Difference: Countries in set_g7 but NOT in set_europe
g7_not_europe = setdiff(set_g7, set_europe)
println("Difference (G7 countries not in Europe): ", g7_not_europe)
# Checking for membership (is an element in a set?)
is_spain_in_europe = "Spain" in set_europe
println("Is Spain in the European set? ", is_spain_in_europe) # Output: true
is_brazil_in_g7 = "Brazil" in set_g7
println("Is Brazil in the G7 set? ", is_brazil_in_g7) # Output: false
Comprehensions provide a concise and readable way to create collections, particularly Arrays and Dictionaries, based on existing iterables or ranges.
1. Array Comprehensions
# Create an array of the first 5 even numbers (starting from 2)
first_five_evens = [2 * i for i in 1:5]
println("First five evens: ", first_five_evens) # Output: [2, 4, 6, 8, 10]
# Create an array of uppercase characters from a string
name_str = "julia"
name_chars_upper = [uppercase(char) for char in name_str]
println("Uppercase characters: ", name_chars_upper) # Output: ['J', 'U', 'L', 'I', 'A']
# Array comprehension with a condition: squares of odd numbers from 1 to 10
odd_squares = [i^2 for i in 1:10 if i % 2 != 0]
println("Squares of odd numbers: ", odd_squares) # Output: [1, 9, 25, 49, 81]
2. Dictionary Comprehensions
Comprehensions can also be used to create dictionaries.
# Create a dictionary mapping numbers (1 to 4) to their string representation
num_to_string_dict = Dict(i => string(i) for i in 1:4)
println("Number to String Dictionary: ", num_to_string_dict)
# Output: Dict(4 => "4", 2 => "2", 3 => "3", 1 => "1") (order may vary)
# Create a dictionary from two lists (one for keys, one for values)
student_names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]
student_score_dict = Dict(student_names[i] => scores[i] for i in 1:length(student_names))
println("Student Score Dictionary: ", student_score_dict)
# Output: Dict("Bob" => 92, "Charlie" => 78, "Alice" => 85) (order may vary)
Practice Task: Analyzing Text Data
Let's try a small task that combines several of these concepts. Suppose you have a piece of text and you want to:
text_sample = "The quick brown fox jumps over the lazy dog. The dog barks."
# 1. Preprocess: Convert to lowercase and split into words.
# Remove punctuation for a cleaner word list (simple approach here).
words_raw = split(lowercase(replace(text_sample, "." => "")))
println("Raw words: ", words_raw)
# 2. Find unique words using a Set
unique_words = Set(words_raw)
println("\nUnique words: ", unique_words)
println("Number of unique words: ", length(unique_words))
# 3. Count word frequencies using a Dictionary
word_frequencies = Dict{String, Int}()
for word in words_raw
# If word is in dict, increment count, otherwise add it with count 1
word_frequencies[word] = get(word_frequencies, word, 0) + 1
end
println("\nWord Frequencies:")
for (word, count) in word_frequencies
if count > 0 # Just to ensure we print actual words if any were filtered
println("'$word': $count")
end
end
This example shows how arrays (from split), sets (for uniqueness), and dictionaries (for frequency counting) can work together to process data.
These exercises cover the fundamental operations for Julia's primary collection types. As you become more familiar with them, you'll find they are indispensable for structuring and managing data in your Julia programs. The best way to learn is by doing, so try modifying these examples or creating your own small projects to further explore their capabilities.
Was this section helpful?
© 2026 ApX Machine LearningEngineered with