Free

3: Building Our First Programs

⏱️ 50-65 minutes
📊 intermediate

Chapter 10: "Arrays and Lists: Treasure Collections"

On the weekend, Professor Bit suggested Alice help sort through his stamp collection. They laid out several albums with stamps from different countries and themes on the table.

— You know, Alice, — the Professor began, flipping through album pages, — collections in real life are very similar to what in programming is called arrays and lists.

— What are arrays and lists? — Alice asked, examining a colorful stamp with an image of a spacecraft.

— Imagine you have many related items that you want to store together, — the Professor explained. — For example, all these stamps in the album. In programming, we can create a list that will contain many elements and work with them as a single whole.

Byte displayed an example on his screen:

python
stamps = ["space", "animals", "sports", "art", "transport"]

— This is a list of five strings, — the Professor explained. — Each string is a separate element of the list, and together they form a collection.

Stamp collection: a list and indexes from 0 to 4

— That simple? — Alice was surprised.

— Yes, creating a list is very simple, — the Professor nodded. — But you can work with it in different ways. For example, we can find out how many elements are in the list:

python
stamp_count = len(stamps) # result: 5

— We can access a specific element by its position (index):

python
first_stamp = stamps[0] # result: "space"
second_stamp = stamps[1] # result: "animals"

— Wait, — Alice frowned, — why does the first element have index 0, not 1?

— Good question! — the Professor smiled. — In most programming languages, indexing starts at zero. This is related to how computers store data in memory. So the first element has index 0, the second — index 1, and so on.

Массив — это длинный сверкающий поезд,
Где выстроен в линию каждый вагон.
С нуля начинает отсчёт эта повесть,
И строго по правилам движется он.

Ты можешь достать из шестого посылку,
А можешь вагон прицепить в самый хвост.
Массивы и списки — не просто копилка,
А к собранным данным проложенный мост!

An array is a train: cars with indexes 0, 1, 2, 3 and an item in each

Logic, who was sorting stamps by category, added:
— Lists in programming are very flexible. We can add new elements, remove existing ones, change them, sort, and so on.

The Professor showed new examples:

python

Adding a new element to the end of the list


stamps.append("architecture")
print(stamps) # ["space", "animals", "sports", "art", "transport", "architecture"]

Removing an element


stamps.remove("sports")
print(stamps) # ["space", "animals", "art", "transport", "architecture"]

Changing an element


stamps[1] = "wildlife"
print(stamps) # ["space", "wildlife", "art", "transport", "architecture"]

Sorting the list alphabetically


stamps.sort()
print(stamps) # ["architecture", "wildlife", "art", "space", "transport"]

— What if I want to check if a certain stamp is in my collection? — Alice asked.

— For this, you can use the in operator, — the Professor explained:

python
if "space" in stamps:
print("You have space-themed stamps!")
else:
print("You don't have space-themed stamps.")

Byte showed a new example on his screen:

python

Iterating through all list elements


for theme in stamps:
print("You have stamps on the theme:", theme)

— With the for loop, we can perform some action for each element of the list, — the Professor explained. — This is very convenient when you need to process all elements of a collection.

— Can we create lists with different data types? — Alice wondered.

— Of course! — the Professor nodded. — You can put numbers, strings, boolean values, and even other lists in one list.

python
mixed = [42, "hello", True, [1, 2, 3]]

— Nested lists are especially useful for representing tabular data or multidimensional structures, — the Professor added. — For example, we can represent a game board for tic-tac-toe:

python
board = [
[" ", " ", " "],
[" ", "X", " "],
[" ", " ", "O"]
]

— In this example, we have a list of three lists, each representing one row of the game board, — he explained. — To access a specific cell, you need to specify two indices:

python
center_cell = board[1][1] # result: "X"

— Are there other types of collections besides lists? — Alice asked.

— Yes, different programming languages have different types of collections, — the Professor replied. — For example, in Python there are:

1. Lists (list) — ordered collections, which we've already discussed
2. Tuples (tuple) — similar to lists, but cannot be changed after creation
3. Dictionaries (dict) — collections of "key-value" pairs, like real dictionaries
4. Sets (set) — unordered collections of unique elements

— Let's look at dictionaries in more detail, — the Professor suggested. — They're very useful when you need to link one data with another.

python

Dictionary linking countries with their capitals


capitals = {
"Russia": "Moscow",
"France": "Paris",
"Japan": "Tokyo"
}

Getting value by key


capitaloffrance = capitals["France"] # result: "Paris"

Adding a new key-value pair


capitals["Italy"] = "Rome"

Iterating through all pairs in the dictionary


for country, capital in capitals.items():
print("Capital of", country, "is", capital)

— In a dictionary, we access elements not by index, but by key, — the Professor explained. — This makes code more understandable and less prone to errors.

— What about sets? — Alice asked. — What are they for?

— Sets are useful when only the presence or absence of an element matters to us, and order doesn't matter, — Logic replied. — In addition, sets automatically remove duplicates.

python

Creating a set


colors = {"red", "blue", "green", "blue"}
print(colors) # result: {"red", "blue", "green"} - duplicate "blue" removed

Checking for element presence


if "yellow" in colors:
print("Yellow color is in the set")
else:
print("Yellow color is not in the set")

Set operations


colors2 = {"yellow", "blue", "orange"}
common_colors = colors & colors2 # intersection: {"blue"}
all_colors = colors | colors2 # union: {"red", "blue", "green", "yellow", "orange"}

— Collections are constantly used in programming, — the Professor summarized. — They allow working with groups of data, which is critically important for most programs.

— It's like in real life, — Alice noticed, closing the stamp album. — We constantly deal with collections: a set of pencils, books on a shelf, groceries in the fridge.

— Exactly! — the Professor smiled. — Programming often reflects structures and processes from the real world, making them more organized and efficient.

Task

Imagine you're creating a program to track your collection (books, toys, stickers — anything). Write an example of a list or dictionary to store information about your collection. Then write several lines of code demonstrating how you can work with this collection (adding new elements, searching, sorting, etc.).