Lists in Python and Vectors in C++: Working with Collections of Data
Learn how to store, access, update, and iterate through multiple values using a single ordered collection in visual blocks, Python lists, and C++ std::vector.
In This Article
- Recognize when an ordered collection is cleaner and more scalable than separate variables.
- Access and modify elements accurately using zero-based indexing without triggering out-of-bounds errors.
- Add new items dynamically and iterate over collections to calculate totals or find maximum values.
- Compare visual list blocks, Python lists, and C++ std::vector containers side by side.
Why Single Variables Are Not Always Enough
When you write your very first programs, storing each piece of data in its own named variable feels natural. You might create score to track points, lives to count remaining attempts, or player_name to store a label. That approach works well when you only have two or three separate values. However, real programs quickly outgrow individual variables.
Imagine building a puzzle game where a player collects items into a backpack, or a leaderboard that records the top fifty high scores, or an undo system that remembers every directional move the player has made since the level started. If you tried to use separate variables like item_1, item_2, item_3, and so on up to item_50, your program would become nearly impossible to maintain. You could not write a loop to inspect all fifty variables at once, and you could not easily add a fifty-first item while the game is running.
To solve this problem, programming languages provide ordered collections—often called arrays, lists, or vectors. Instead of inventing a brand-new variable name for every single value, you create one container variable that holds a sequence of items in a specific order. Every item inside the collection sits in a numbered slot called an index.
Zero-Based Indexing: Why Counting Starts at Zero
In everyday conversation, we call the initial item in a line the "first" item (position 1). In almost all modern text-based programming languages—including Python, C++, Java, and JavaScript—positions inside a collection are numbered starting at 0. The first element is at index 0, the second element is at index 1, and the third element is at index 2.
Why do computers count from zero? Historically, an index represents an offset—how many steps you must move forward from the beginning of the collection in memory to reach the desired element. To read the very first item, you move zero steps away from the start, so its offset is 0. To read the next item, you step forward by one slot, so its offset is 1.
This creates a vital rule that every programmer must memorize: if a list contains N items, the valid indices run from 0 up to N - 1. For example, if your inventory list holds 4 items, their indices are 0, 1, 2, and 3. There is no item at index 4.
When your code asks for an index that does not exist—such as index 4 in a four-item list, or a negative index in C++—you trigger an out-of-bounds error. In Python, the interpreter immediately stops and raises an IndexError: list index out of range. In C++, using square brackets my_vector[4] on a four-item vector is even more dangerous because it reads raw memory outside the vector without warning, though using the safer my_vector.at(4) method will throw an std::out_of_range exception just like Python.
Note that some beginner visual block environments (such as Scratch) number list slots starting at 1 to feel familiar to younger learners, while computer-science block environments (such as Blockly and CodeCracker's logic puzzles) often use 0 so the transition to Python and C++ is seamless. Always check whether your block environment starts at 0 or 1!
Creating, Reading, and Updating Collections
Regardless of the language you choose, there are four core operations you perform on any list or vector:
- Create (Initialize): Define the collection, either starting empty or pre-filled with initial values.
- Read (Access): Look up the value stored at a specific index without changing it.
- Update (Mutate): Overwrite the value at a specific index with a new value.
- Append (Push): Attach a brand-new element to the end of the collection, increasing its length by one.
Notice an important difference between Python and C++ when creating a collection: a Python list is dynamically typed, meaning it can hold numbers or strings immediately without declaring a type first. A C++ std::vector is statically typed, so you must specify the type of data it holds inside angle brackets, such as std::vector<int> for integers or std::vector<std::string> for text.
Visual Block Logic
SET scores TO [120, 95, 140]
APPEND 160 TO scores
SET item AT index 1 OF scores TO 110
PRINT (item AT index 0 OF scores)
PRINT (LENGTH OF scores)
Python
scores = [120, 95, 140]
scores.append(160)
scores[1] = 110
print(scores[0])
print(len(scores))
C++
#include <iostream>
#include <vector>
int main() {
std::vector<int> scores = {120, 95, 140};
scores.push_back(160);
scores[1] = 110;
std::cout << scores[0] << "
";
std::cout << scores.size() << "
";
return 0;
}
Let us trace what happens to scores in the code above:
- Initially,
scorescontains three elements: index0is120, index1is95, and index2is140. - After appending
160(using.append()in Python or.push_back()in C++), the collection has four elements:[120, 95, 140, 160]. - Next, we update index
1to110. Remember that index1is the second item! The collection now holds[120, 110, 140, 160]. - Finally, printing index
0outputs120, and printing the length outputs4.
Looping Over a Collection: Sum and Maximum
The true power of lists and vectors appears when you combine them with loops. Instead of writing separate lines of code to inspect each slot, a loop visits every element from start to finish automatically. Two classic beginner algorithms are calculating the total sum of all values and finding the maximum value in a list.
To find the sum, we create an accumulator variable called total initialized to 0, and add each item to total as we loop. To find the maximum value, we initialize highest to the very first item in the list (at index 0), and then compare every item against highest. Whenever we see a number larger than highest, we update highest to that number.
Visual Block Logic
SET coins TO [15, 42, 8, 60, 25]
SET total TO 0
SET highest TO (item AT index 0 OF coins)
FOR EACH value IN coins DO
CHANGE total BY value
IF value > highest THEN
SET highest TO value
END IF
END FOR
PRINT "Total:", total
PRINT "Max:", highest
Python
coins = [15, 42, 8, 60, 25]
total = 0
highest = coins[0]
for value in coins:
total += value
if value > highest:
highest = value
print("Total:", total)
print("Max:", highest)
C++
#include <iostream>
#include <vector>
int main() {
std::vector<int> coins = {15, 42, 8, 60, 25};
int total = 0;
int highest = coins[0];
for (int value : coins) {
total += value;
if (value > highest) {
highest = value;
}
}
std::cout << "Total: " << total << "
";
std::cout << "Max: " << highest << "
";
return 0;
}
Why did we initialize highest = coins[0] instead of highest = 0? Suppose a list contained only negative numbers, such as temperatures below freezing: [-12, -5, -20]. If highest started at 0, none of the negative numbers would be greater than 0, and your program would falsely claim that 0 was the highest temperature in the list! Starting with the actual first element at index 0 guarantees that highest is always a genuine member of the collection.
Try It Yourself
Challenge: Filter and Count Passing Levels
Suppose a player completed six puzzle stages and earned the following star ratings stored in a collection: [3, 1, 2, 3, 0, 2]. A stage counts as "mastered" only if the star rating is 2 or higher.
- Create a collection named
starscontaining[3, 1, 2, 3, 0, 2]. - Before looping, the player replays the fifth stage (which currently has
0stars) and earns3stars. Write a single statement using zero-based indexing to update that specific slot from0to3. (Hint: What index is the fifth element?) - Write a loop that steps through every rating in
starsand counts how many stages have a rating greater than or equal to2. - Print the final count of mastered stages (your output should be
5).
CodeCracker