"

9 Introduction to Lists

Hasan Malik and Rutwa Engineer

Learning Objectives

  • Learn what are lists in Lua
  • Learn to access, add, and remove elements in a list
  • Learn how to find the length of a list
  • Learn to loop through a list using a basic for loop and using ipairs()
  • Learn how to sort a list

Introduction

A list is a collection of items. For example, you could have a list of fruits, a list of colours, a list of games, etc.

Creating a List

Example

local fruits = {“apples”, “bananas”, “cherries”}

Let’s dissect this example carefully!

Lists are demarcated using curly brackets {}.

We say the 1st element of the list fruits is “apples”. The 2nd element is “bananas” and the 3rd element is “cherries”.

The programming terminology for the position of an element in a list is its index. We say “apples” is at index 1, “bananas” is at index 2, and so on.

Accessing Elements

Example

We can access elements of a list in the following way:

local colors = {"red", "green", "blue"}

print(colors[1])  -- Output: red

print(colors[2])  -- Output: green

print(colors[3])  -- Output: blue


colors[1] refers to the element in the colors list at index 1. colors[2] refers to the element in the colors list at index 2.

Key Takeaway

We write the index number within square brackets [].

Adding New Elements

local animals = {"dog", "cat"}

Let’s say we want to add another animal to our list above, e.g. “lion”. We can do that in the following way:

animals[3] = "lion"

print(animals[3])  -- Output: lion

This means that we have stored “lion” at index 3 in the list.

Similarly, we can say animals[4] = "snake" to add another animal.

Now, let’s say we change our mind and want to replace “snake” with some other animal, e.g. “giraffe”. We can do this in the following way:

animals[4] = “giraffe”

This is called overwriting. The list now stores “giraffe” at index 4. The “snake” element has been deleted.

Removing elements from a list; Checking the length

To remove an element from a list, we use the table.remove() function.

Examples

local games = {“chess”, “jenga”, “ludo”}

table.remove(games, 2)


This will remove the element at index 2, i.e. “jenga”.

How can we verify that our code is working? Answer – the length function!

Recall, in Module 2, we learnt that the # operator can be used to find the length of a string. Similarly, we can also use it to find the length of a list.

local games = {“chess”, “jenga”, “ludo”}

print(#games)

This will output 3, because that is the length of the games list (i.e. the number of elements in the games list is 3).

table.remove(games, 2)

print(#games)

Now, this will output 2, because one element has been removed from the games list.

Looping Through Lists

There are two ways of looping through a list using a for loop.

Strategy 1: Looping using an index variable

Let’s say I have a list of numbers, and I want to print each element of my list. How can I do that?

Answer – use a for loop!


for i=1, #numbers do

print(numbers[i])

end


Now, there’s a lot of stuff going in that above code, so let’s break it down slowly!

We are using the basic for loop structure you learnt earlier. The starting index of i is 1. The ending index is #numbers, i.e. the length of the numbers list, which in this case is 9.

Now, the statement print(numbers[i]) is really quite clever. It is simply printing the element at index i of numbers. When we begin iterating through the loop, the value of i is 1, so the first element of the list – namely, 4 – is printed. Then, on the second iteration, the value of i is 2, so the second element – namely, 7 – is printed, and so on until the final element of the list – which has the index 9, i.e. #numbers – is printed.

Thus, our code outputs:

4

7

8

4

2

0

1

7

5

Strategy 2: Looping using ipairs()

Let’s say I have a list of car companies, and I want to print the name of each company.


local cars = {"Toyota", "Ford", "Honda"}

for i, car in ipairs(cars) do

print(i, car)

end


Here, we use the ipairs() function to loop through the list. We write the name of our list, i.e. cars, in between the parentheses. The ipairs() function takes control of the i and car variables, and updates their values as we loop through the list.

Initially, i is set to 1 and car is set to cars[i], which is equivalent to cars[1], which is “Toyota”. Thus, on the first iteration, we print:

1 Toyota

Then, on the next iteration, i is incremented to 2, and car is automatically set to cars[i], which is equivalent to cars[2], which is “Ford”. And so, we print:

2 Ford

And similarly, we print:

3 Honda

This is a useful and simple way of outputting each element of the list beside its index number.

Suppose that you only want to output the car company’s name, and not its corresponding index number. To do this, you can change the print statement. Rather than print(i, car), just write print(car). This will result in the output:


Toyota

Ford

Honda


Because i is not being printed.

Try to print each list we have discussed in our examples above – such as animals, colors, games, etc – using both methods for practice!

Exercises

  • Print the name of each car company using Strategy 1.
  • Create a list of your 5 favourite foods and print them.
  • Add a new food item, remove one item, and print the updated list.

Sorting Lists

In data analysis, it is often useful to store data in an orderly sequence. Using lists in Lua, we can automatically sort large chunks of data.

Examples

local numbers = {1, 9, 97, -90, 43, 67.3, 22.8, 3.14, 2.71, 893, 901, -203, 456, 5}

Suppose you wanted to arrange the numbers list in ascending order. It would be very tedious to manually figure out the correct order of the numbers, and then type out the new list. It would also be error-prone, especially if the list was very large, because humans are not naturally good at remembering large chunks of information.

So, we can use the table.sort function:

local numbers = {1, 9, 97, -90, 43, 67.3, 22.8, 3.14, 2.71, 893, 901, -203, 456, 5}

table.sort(numbers)

And, voila! Your list is perfectly sorted!

But how can you verify this?

Let’s print the list before and after the sorting:


local numbers = {1, 9, 97, -90, 43, 67.3, 22.8, 3.14, 2.71, 893, 901, -203, 456, 5}

 

for i, num in ipairs(numbers) do

print(num)

end

 

print()

 

table.sort(numbers)

 

for i, num in ipairs(numbers) do

print(num)

end


Note: The print() statement in line 7 is intended merely to create some space, i.e. an empty line, between the first printing of list and the second printing of the list.

This will output:


1

9

97

-90

43

67.3

22.8

3.14

2.71

893

901

-203

456

5

 

-203

-90

1

2.71

3.14

5

9

22.8

43

67.3

97

456

893

901


Ta-da! You can see your list has been sorted into ascending order.

Example

Similarly, we can sort a list of strings. Just like table.sort() organizes numbers into ascending order, it also organizes strings into alphabetical order.


local fruits = {"banana", "apple", "cherry", "date"}

table.sort(fruits)

for i, fruit in ipairs(fruits) do

print(fruit)

end


Output:

apple

banana

cherry

date

 

Exercise

local marks = {50.5, 24.6, 34.0, 93.4, 40.5, 21.9, 41.0, 60.6, 6.0, 59.3, 75.4, 50.0, 58.0, 88.0, 61.1, 17.0, 23.3, 31.0, 89.8, 7.4} is a list of marks gained by students in a recent exam. Use table.sort() to find the highest mark obtained.

Congratulations—you are now familiar with lists in Lua!

 

 

License

Learn Coding and Animations in Lua Code Copyright © by Kyra Ma; Hasan Malik; and Rutwa Engineer. All Rights Reserved.