Skip to main content
Skip to content

Lesson 8 of 12

Lists: store many values in order

Keep many values in one variable, reach any item by position, and use the list helpers to add, remove, sort, sum and search.

11 min

Creating a list and reading items

Square brackets make a list: ["Aam", "Kela", "Seb"]. Each item has a position called an index, starting at 0, so fal[0] is the first item. lambai(list) gives the number of items. Reading a position that does not exist gives khali rather than an error.

You can change an item by assigning to its index: fal[1] = "Chiku";.

Expected output

Press Run to try it

AamKitne fal: 3[Aam, Chiku, Seb]khali

Looping over a list

A chalo loop from 0 up to lambai(list) visits every item. This is the pattern you will write most often.

Expected output

Press Run to try it

Subject 1 : 78Subject 2 : 91Subject 3 : 64

Adding and removing

jodo(list, item) ("add") puts an item at the end. nikalo(list) ("take out") removes the last item and gives it back. Both change the original list.

Expected output

Press Run to try it

[padhai, gym, khana]Hata diya: khana | Bacha: [padhai, gym]

Helpers that save you a loop

kul(list) adds up numbers. chhanto(list) ("sort") returns a sorted copy — numbers by value, text alphabetically — and leaves the original alone. ulta(list) returns a reversed copy. kram(start, end) builds a list of numbers from start up to, but not including, end.

shamil(list, item) answers sahi/galat: is the item in the list? khojo(list, item) gives its index, or -1 if it is missing. tukda(list, start, end) cuts out a slice.

Expected output

Press Run to try it

71[3, 7, 19, 42][3, 19, 7, 42][1, 2, 3, 4, 5]sahi 2 -1[7, 19]

Practice exercise

For rakho runs = [12, 45, 7, 88, 30]; print the total runs, the highest score (use chhanto and take the last item) and the number of innings. Expected: Total: 182, Best: 88, Innings: 5.

Expected output

Total: 182
Best: 88
Innings: 5
Open in playground
Show solution
solution.altf
rakho runs = [12, 45, 7, 88, 30];
rakho sorted = chhanto(runs);
bol("Total:", kul(runs));
bol("Best:", sorted[lambai(sorted) - 1]);
bol("Innings:", lambai(runs));