English:Arrays and Lists

Arrays and Lists
Introduction
Arrays and Lists are ways to organize many related values so that a program can work with them as a group. Instead of creating a separate variable for every score, name, temperature, or sensor reading, you can store the values in an ordered collection and process them with the same algorithm.
This aiMOOC is designed for Grades 9–10. You should already be familiar with variables, simple conditionals, and loops. You will learn how arrays and lists represent sequences, how indexing works, how to read and update elements, how to traverse collections, and how to choose a suitable structure for a programming task.
By the end of the course, you should be able to explain the difference between an array and a list, trace code that changes a sequence, write small programs that search or summarize data, use nested collections, and reason about common errors such as invalid indexes.
Why Collections Matter
Imagine a class survey with 28 responses. Storing the answers in 28 separate variables would make the program repetitive and difficult to maintain. A collection gives the data a shared structure. This lets you ask useful questions such as: What is the first value? What is the largest value? How many values meet a condition? Where does a target value occur?
Collections are central to computer science because data often arrives as sequences: words in a sentence, pixels in an image, daily temperatures, player scores, products in a cart, or measurements from an experiment. Arrays and lists help you move from individual values to algorithms that work on whole datasets.
Learning Goals
- Indexing: Use indexes correctly to access and update elements.
- Iteration: Traverse a sequence with loops and explain each step.
- List operations: Add, remove, replace, and search for values.
- Two-dimensional data: Model rows and columns with nested collections.
- Algorithmic thinking: Compare solutions and predict how work grows as a collection becomes larger.
Arrays: Ordered Data by Position
An array stores a sequence of elements that can be identified by position. In many languages, the elements of a basic array have the same type and the array has a fixed length once it is created. The exact rules depend on the programming language, so you should always check the language you are using.
Most modern introductory languages use zero-based indexing. That means the first element is at index 0, the second is at index 1, and the final element of a collection of length n is usually at index n − 1.
For example, consider the sequence of scores 12, 18, 15, 20. With zero-based indexing, the positions are:
| Index | Value |
|---|---|
| 0 | 12 |
| 1 | 18 |
| 2 | 15 |
| 3 | 20 |
The value 15 is at index 2. Notice that the human phrase “third item” and the computer index “2” describe the same element in a zero-based system.
Reading and Updating Elements
An element is one stored item. An index identifies a position. In languages that use square-bracket notation, an expression such as scores[2] reads the element at index 2.
A Python-style example makes the idea easy to see:
scores = [12, 18, 15, 20]
print(scores[0]) # first element: 12
print(scores[2]) # third element: 15
scores[1] = 19 # replace 18 with 19
print(scores)After the assignment, the sequence is [12, 19, 15, 20]. The length has not changed because one value was replaced by another.
A useful tracing habit is to write the index and current value in a small table whenever you are unsure what a line of code does.
Length and Valid Indexes
If a zero-based sequence has length 5, its valid indexes are 0, 1, 2, 3, and 4. Index 5 is outside the valid range. Trying to access an invalid position may cause an error or return a special value, depending on the language.
The rule to remember is:
For a zero-based sequence of length n, the last valid index is n − 1.
This is why loops often continue while an index is less than the length rather than less than or equal to the length.
names = ["Ava", "Ben", "Chen", "Dina"]
for i in range(len(names)):
print(i, names[i])This loop visits indexes 0 through 3. It never attempts index 4.
Arrays and Memory
A classical array is designed so that an element can be found quickly from its index. Many array implementations place equal-sized elements in a regular memory layout, allowing the computer to calculate where an indexed element is stored.
At Grades 9–10, you do not need to calculate memory addresses. The important idea is that arrays are built for efficient access by position. This is one reason arrays are useful for tables, measurements, images, game boards, and other data where positions matter.
Lists: Flexible Sequences
A list in computer science is an ordered finite sequence of items. The word “list” can describe an abstract idea as well as a concrete data structure. A list usually supports operations such as reading items, inserting items, deleting items, and traversing the sequence.
In Python, the built-in list is a mutable sequence whose size can grow or shrink. In Java, a basic array has a fixed length, while an ArrayList is designed to resize. In JavaScript, Array objects are resizable. These language differences are why it is better to learn the underlying concepts instead of assuming that every language uses the same rules.
Common List Operations
Consider this Python list:
tasks = ["read", "code", "test"]You can perform several common operations:
tasks.append("reflect") # add at the end
tasks.insert(1, "plan") # insert at index 1
tasks[2] = "program" # replace one item
tasks.remove("test") # remove the first matching value
last_task = tasks.pop() # remove and return the final itemThese operations change the list. A structure that can be changed after creation is called mutable.
When you read code, distinguish carefully between three different actions: accessing an item, replacing an item, and changing the length of the collection.
Arrays, Dynamic Arrays, and Linked Lists
The terms can be confusing because different structures can provide a similar “list-like” experience.
| Structure | Main idea | Size behavior | Position access |
|---|---|---|---|
| Basic array | Elements are arranged for direct indexed access | Often fixed after creation | Usually fast |
| Dynamic array | An array-based structure that can resize | Can grow or shrink | Usually fast |
| Linked list | Each node stores data and a link to another node | Can grow or shrink | Requires following links to reach a position |
A linked list illustrates that a “list” does not have to be stored like an array.
A Python list should not be confused with a textbook linked list. It behaves as a resizable indexed sequence. For this course, focus first on the operations you need and then on how different structures support those operations.
Traversing a Collection
To traverse a collection means to visit its elements in a systematic order. Loops make this possible.
If you only need each value, a direct loop is often simplest:
temperatures = [16, 18, 21, 19]
for temperature in temperatures:
print(temperature)If you need both the index and the value, you can use an indexed loop or a language feature that provides both:
temperatures = [16, 18, 21, 19]
for index, temperature in enumerate(temperatures):
print(index, temperature)Ask yourself what information your algorithm needs. If the position itself is important, keep the index. If only the values matter, a direct element loop can be clearer.
Accumulation: Building a Result
Many collection algorithms maintain a result while they traverse the data. This pattern is called accumulation.
scores = [7, 9, 6, 10, 8]
total = 0
for score in scores:
total = total + score
average = total / len(scores)
print(average)The variable total changes after each element. You can trace the algorithm by recording the current score and the new total after every loop iteration.
Other accumulation tasks include counting values that satisfy a condition, joining pieces of text, and building a new list.
Filtering: Selecting Some Elements
Filtering means keeping items that satisfy a rule.
scores = [7, 9, 6, 10, 8]
high_scores = []
for score in scores:
if score >= 9:
high_scores.append(score)
print(high_scores)The result is [9, 10]. The original list remains unchanged in this example because the matching values are copied into a new list.
Filtering is useful in real applications such as selecting affordable products, finding measurements above a threshold, or displaying messages from a chosen sender.
Searching: Finding a Target
A linear search checks elements one after another until the target is found or the collection ends.
names = ["Ava", "Ben", "Chen", "Dina"]
target = "Chen"
found_index = -1
for i in range(len(names)):
if names[i] == target:
found_index = i
break
print(found_index)The result is 2. The special value -1 is used here to mean “not found.” Different languages and libraries use different conventions.
For an unsorted list, linear search may need to inspect every element. If the amount of data doubles, the worst-case amount of checking also roughly doubles. This is an introduction to algorithmic complexity.
Nested Arrays and Lists
A collection can contain other collections. This creates nested structures. A two-dimensional arrangement is useful for data organized in rows and columns, such as a game board, seating chart, spreadsheet, or small image.
A Python example:
grid = [
["A", "B", "C"],
["D", "E", "F"],
["G", "H", "I"]
]
print(grid[1][2])The first index chooses row 1, which is the second row. The second index chooses position 2 in that row, which is the third element. The output is F.
Traversing Rows and Columns
Nested loops can visit every cell:
grid = [
[2, 4, 6],
[1, 3, 5]
]
for row in grid:
for value in row:
print(value)The outer loop chooses one row at a time. The inner loop visits each value in the current row.
A useful debugging technique is to trace the two loop variables separately. Ask: Which row am I in? Which value inside that row am I processing?
Beyond Two Dimensions
Arrays can have more than two dimensions. A three-dimensional structure can model layers of data, such as several 2D images, measurements across time, or a block of cells.
For most school projects, one- and two-dimensional structures are enough. The important transferable idea is that each additional dimension requires another position or index to locate one value.
Choosing Between Arrays and Lists
There is no single structure that is best for every problem. Make your choice based on what the program needs to do.
Use an array-like structure when positions matter, indexed access is frequent, or the amount of data is known and stable. Use a resizable list-like structure when items are added or removed often or when the final size is not known in advance.
Before choosing, ask these questions:
- Data modeling: Is the data naturally ordered?
- Index: Do I need frequent access by position?
- Mutation: Will the number of items change while the program runs?
- Traversal: Will I usually process every item in sequence?
- Performance: Which operations happen most often?
These questions are more useful than memorizing a rule such as “arrays are always better” or “lists are always easier.”
Performance Intuition
For a typical array or dynamic array, reading an element by index is usually very fast because the position can be calculated directly. A linear search through an unsorted sequence may inspect many elements. Inserting or deleting near the middle of an array-based sequence may require other elements to shift.
A linked list has different trade-offs. Reaching the item at a given position requires following links from node to node, but inserting a node can be efficient when the program already has a reference to the correct location.
At this level, focus on the shape of the work:
| Operation | Typical array-based intuition | Question to ask |
|---|---|---|
| Read by index | Very efficient | Do I know the position? |
| Linear search | Work grows with the number of elements | Is the data unsorted? |
| Append to a dynamic array | Usually efficient | Can occasional resizing happen? |
| Insert in the middle | May require shifting elements | How often will this occur? |
The word typical matters. Exact performance depends on the language, implementation, and operation.
Common Errors and Debugging
Collections are a common source of small but important programming mistakes. Learning to diagnose them is part of learning the structure.
Off-by-One Errors
An off-by-one error occurs when a boundary is one position too early or too late. A common example is trying to access index len(items) in a zero-based list. The last valid index is len(items) - 1.
Wrong idea:
items = ["red", "green", "blue"]
print(items[len(items)])Correct final element:
items = ["red", "green", "blue"]
print(items[len(items) - 1])A safer alternative in Python is items[-1], but remember that negative indexing is a Python feature and is not universal across programming languages.
Changing a List While Traversing It
Removing items from a list while a loop is moving through that same list can cause elements to be skipped or produce confusing behavior.
Instead of modifying the list immediately, you can often build a new filtered list:
values = [3, 8, 2, 9, 4]
kept = []
for value in values:
if value >= 5:
kept.append(value)
print(kept)The result is [8, 9]. This approach separates the original input from the output and is often easier to reason about.
Aliasing and Shared References
Two variables can sometimes refer to the same mutable list. Then a change made through one variable is visible through the other.
a = [1, 2, 3]
b = a
b.append(4)
print(a)The output is [1, 2, 3, 4] because a and b refer to the same list object.
If you need a separate list, create a copy using an appropriate operation for your language. This becomes especially important with nested collections, where shallow and deep copies can behave differently.
Worked Example: Class Temperature Data
Suppose a class records the outdoor temperature at noon for five school days:
temperatures = [17, 19, 21, 18, 20]You want to calculate the average and count the number of days at or above 20 degrees Celsius.
temperatures = [17, 19, 21, 18, 20]
total = 0
warm_days = 0
for temperature in temperatures:
total += temperature
if temperature >= 20:
warm_days += 1
average = total / len(temperatures)
print("Average:", average)
print("Warm days:", warm_days)The program uses one collection and two accumulators. The loop visits every element once. The variable total stores a running sum, while warm_days stores a running count.
To extend the program, you could find the highest value, record which day it occurred, or compare two weeks using a nested list.
Language Comparison
The same concepts appear under different names in different languages.
| Concept | Python | Java | JavaScript |
|---|---|---|---|
| Resizable sequence | list
|
ArrayList
|
Array
|
| Fixed-size basic array | Not the usual built-in list model | type[]
|
Use specialized structures when fixed-size behavior is required |
| First index | Usually 0 | 0 | 0 |
| Add to end | append
|
add
|
push
|
| Number of items | len
|
length for arrays or size for ArrayList
|
length
|
Do not memorize the syntax without understanding the operations. The transferable idea is the same: create a sequence, identify positions, traverse elements, and transform the data.
Interactive Tasks
Quiz: Test Your Knowledge
In a zero-based array, what is the index of the first element? (0) (!1) (!2) (!The length)
A zero-based list has length 6. What is its last valid index? (5) (!6) (!7) (!4)
What does an index identify in an array or list? (A position of an element) (!The programming language) (!The total memory of the computer) (!The name of every variable)
Which operation changes a value without necessarily changing the length of a list? (Replace an element) (!Append an element) (!Remove an element) (!Insert an element)
What does it mean to traverse a list? (Visit its elements systematically) (!Delete every element) (!Rename the list) (!Convert every value to text)
Which algorithm checks elements one after another for a target? (Linear search) (!Binary encoding) (!Recursion tree) (!Hash encryption)
What is a nested list? (A list that contains another list) (!A list with no elements) (!A list that cannot change) (!A list stored in a text file)
Why are off-by-one errors common with zero-based indexing? (The final index is one less than the length) (!Arrays always begin at index two) (!Loops cannot access arrays) (!Lists never have a length)
Which statement best describes a Python list? (It is a mutable ordered sequence) (!It is always fixed at one length) (!It can store only integers) (!It has no indexes)
When might a two-dimensional collection be especially useful? (Modeling rows and columns) (!Storing one isolated number) (!Naming one variable) (!Printing one fixed sentence)
Memory Game
| Index | Position used to identify an element |
| Element | One item stored in a collection |
| Traversal | Systematic visit through a sequence |
| Append | Operation that adds an item to the end |
| Mutable | Able to be changed after creation |
| Nested | Containing another collection inside |
Drag and Drop
| Match the correct terms. | Topic |
|---|---|
| Append | Add an item to the end |
| Index | Identify an item by position |
| Traverse | Visit elements in sequence |
| Filter | Keep items that satisfy a rule |
| Replace | Change the value at an existing position |
...
Crossword Puzzle
| Index | What word names the position used to access an item? |
| Element | What word names one item stored in a collection? |
| Iterate | What verb means to repeat a process through collection items? |
| Mutable | What adjective describes a collection that can be changed? |
| Matrix | What word often describes data arranged in rows and columns? |
| Bounds | What word describes the valid limits of array indexes? |
LearningApps
Cloze Text
Open-Ended Tasks
Easy
- Indexing poster: Create a one-page visual poster that shows a five-item list with its zero-based indexes, then add two examples of correct element access.
- Trace table: Write a trace table for a loop that adds the values in a short list and explain how the accumulator changes after each iteration.
- Mini list program: Create a small program that stores five favorite books, games, foods, or places in a list and prints the first, middle, and last items.
- Teach indexing on video: Record a short video in which you explain zero-based indexing to a classmate using a real-world row of objects as your model.
Standard
- Debugging investigation: Create three short code examples with index errors, diagnose each problem, and write a corrected version with an explanation.
- Class survey dataset: Conduct a small class survey with permission, store the non-sensitive responses in a list, and write a program that counts or summarizes the results.
- Collection interview: Interview a teacher, technician, librarian, or another adult about a task that involves ordered data, then describe how an array or list could model that data.
- Grid project: Build a two-dimensional list that represents a seating plan, game board, pixel pattern, or timetable and write code that reads and changes selected cells.
Advanced
- Search experiment: Create lists of different lengths, run a linear search for targets near the beginning and end, record the number of comparisons, and explain the pattern you observe.
- Language comparison report: Compare array or list operations in two programming languages and write a short report showing similarities, differences, and one potential source of confusion.
- Real-world collection model: Visit a suitable place such as a school library, computer lab, workshop, or sports area and design a data model that represents one ordered collection you observe without collecting personal data.
- Data explainer project: Produce an illustrated article or video that teaches when to use a one-dimensional list, a two-dimensional collection, and a resizable sequence, including original examples and code.
Learning Assessment
- Trace and justify: Trace a program that updates several list elements, state the final list, and justify each change by referring to indexes and operations.
- Design a solution: Choose an appropriate array or list representation for a school-related dataset and explain why the structure fits the required operations.
- Debug and transfer: Repair a program with an invalid index and then explain how the same error could appear in a different programming language.
- Algorithm comparison: Compare two ways to find a value in a collection and reason about which method is suitable for an unsorted dataset.
- Nested data reasoning: Given a small two-dimensional collection, identify several values by row and column and write code that visits every element.
- Mutation analysis: Explain the difference between replacing an element, appending an element, and removing an element, then predict how each operation changes length and indexes.
Evidence of Learning
Strong evidence of learning includes both understanding and practical performance.
| Area | Evidence |
|---|---|
| Knowledge | You can explain element, index, length, traversal, mutation, nesting, and linear search in your own words. |
| Skills | You can access, update, append, remove, traverse, filter, and search sequence data with correct index logic. |
| Products | You can create trace tables, working programs, diagrams, short explanations, and a small data-modeling project. |
| Reasoning | You can predict the result of code before running it and explain why an index or boundary is valid or invalid. |
| Transfer | You can recognize arrays and lists across more than one programming language and adapt the same algorithmic idea to different syntax. |
| Reflection | You can identify an error in your own approach, describe how you found it, and explain how you would prevent it in future work. |
OERs on the Topic
The following English Wikipedia article provides additional background on arrays as data structures:
You can also explore lists, linked lists, dynamic arrays, linear search, and computational complexity as connected topics.
Linked Learning Areas
The central ideas of this course connect data organization with algorithms, programming language syntax, debugging, and real-world modeling.
aiMOOC Projects
MOOCwiki · Deutsch
Nach dem Lernen ist vor dem Lernen
Entdecke direkt den nächsten Lernkurs. Weitere Inhalte erscheinen, wenn Du weiter nach unten scrollst.
Zur MOOCwiki-HauptseiteMediathek
Mediathek
Mediathek wird aus dem Wiki geladen ...
Keine passenden Inhalte gefunden. Bitte ändere Suche oder Filter.
NEWSLernweltNOAH fragen