2. Programming Fundamentals

Data Structures Basics

Introduce arrays, lists, stacks, and dictionaries with usage patterns, advantages, and simple implementation examples.

Data Structures Basics

Hey students! šŸ‘‹ Welcome to one of the most fundamental topics in computer science - data structures! Think of data structures as different types of containers that help us organize and store information in our programs. Just like how you might use different containers in your room (a bookshelf for books, a drawer for clothes, a box for games), programmers use different data structures depending on what kind of data they're working with and how they need to access it. By the end of this lesson, you'll understand the four essential data structures: arrays, lists, stacks, and dictionaries, along with when and why to use each one.

Arrays: The Foundation of Data Storage šŸ“Š

Arrays are like a row of lockers in a school hallway - each locker has a number (called an index), and you can store one item in each locker. In programming, an array is a collection of elements that are stored in consecutive memory locations, and each element can be accessed using its position number.

Let's say you want to store the test scores for your class of 30 students. Instead of creating 30 separate variables (score1, score2, score3...), you can create one array called testScores that holds all 30 values. In most programming languages, arrays start counting from 0, so the first student's score would be at position 0, the second at position 1, and so on.

Example: testScores = [85, 92, 78, 96, 88]

To access the third score (78), you would use testScores[2] because we count from 0.

Arrays are incredibly fast for accessing data because the computer knows exactly where each element is stored in memory. If you know the index, you can retrieve any element in constant time - it doesn't matter if the array has 10 elements or 10,000 elements! However, arrays have a fixed size in many programming languages, which means you need to decide how many elements you'll need before you create the array. This can be limiting if you're not sure how much data you'll be working with.

Arrays are perfect for situations where you know the size of your data in advance and need quick access to elements by their position. Think of storing pixel colors in an image, daily temperatures for a month, or student grades in a class roster.

Lists: Flexible and Dynamic Collections šŸ“

While arrays are like a fixed row of lockers, lists are more like a stretchy accordion folder that can expand and shrink as needed. Lists (also called dynamic arrays in some contexts) are similar to arrays but with the superpower of being able to change size during program execution.

Imagine you're creating a shopping app, and users can add or remove items from their cart. You don't know in advance whether someone will buy 2 items or 20 items. This is where lists shine! You can start with an empty list and keep adding items as the user shops.

Example: Starting with shoppingCart = [], you can add items:

  • Add milk: shoppingCart = ["milk"]
  • Add bread: shoppingCart = ["milk", "bread"]
  • Add eggs: shoppingCart = ["milk", "bread", "eggs"]

Lists support many useful operations like inserting elements at any position, removing elements, and finding the length of the list. Most modern programming languages provide built-in list types (like Python's list, Java's ArrayList, or JavaScript's Array) that handle the memory management automatically.

The trade-off with lists is that some operations can be slower than arrays. For example, inserting an element in the middle of a large list requires shifting all the subsequent elements to make room, which takes more time as the list grows. However, adding elements to the end of a list is usually very fast.

Lists are ideal when you need flexibility in data size, such as storing user inputs, managing game inventories, or collecting search results where the number of items can vary significantly.

Stacks: Last In, First Out (LIFO) šŸ„ž

A stack is like a stack of pancakes or a pile of books - you can only add new items to the top, and when you want to remove something, you take it from the top as well. This behavior is called "Last In, First Out" or LIFO for short.

Think about the "undo" function in your favorite text editor or image editing software. Every action you perform gets "pushed" onto a stack. When you press Ctrl+Z, the program "pops" the most recent action off the stack and undoes it. If you keep pressing undo, it works backwards through your actions in reverse order - exactly how a stack works!

Stack Operations:

  • Push: Add an element to the top of the stack
  • Pop: Remove and return the top element from the stack
  • Peek/Top: Look at the top element without removing it
  • isEmpty: Check if the stack is empty

Real-world example: Your web browser uses a stack to keep track of the pages you visit. Each time you click a link, the new page gets pushed onto the stack. When you hit the "back" button, the browser pops the current page off the stack and shows you the previous one.

Stacks are incredibly useful in programming for managing function calls (the call stack), parsing mathematical expressions, and implementing undo functionality. They're simple but powerful, and understanding stacks will help you grasp more complex algorithms later in your computer science journey.

Dictionaries: Key-Value Powerhouses šŸ—ļø

Dictionaries (also called hash maps, associative arrays, or objects in different languages) are like a real dictionary or phone book - instead of looking up information by position (like in arrays), you look it up by a unique key. Each piece of data (value) is associated with a unique identifier (key).

Imagine you're building a student database. Instead of remembering that "John Smith's grade is at position 7 in the array," you can use a dictionary where the student's name is the key and their grade is the value. This makes your code much more readable and logical!

Example:

studentGrades = {
    "Alice Johnson": 94,
    "Bob Smith": 87,
    "Carol Davis": 91,
    "David Wilson": 85
}

To find Alice's grade, you simply use studentGrades["Alice Johnson"] instead of trying to remember her position in an array.

Dictionaries excel when you need to associate related pieces of information or when you want to look up data using meaningful identifiers rather than numeric positions. They're incredibly fast for lookups - finding a value by its key typically takes the same amount of time regardless of how many items are in the dictionary.

Common uses for dictionaries include storing user profiles (username as key, profile data as value), caching computed results (input as key, result as value), and counting occurrences of items (item as key, count as value). Social media platforms use dictionaries extensively - think about how Instagram maps usernames to profile information, or how Twitter associates hashtags with lists of posts.

The main limitation of dictionaries is that keys must be unique - you can't have two entries with the same key. Also, unlike arrays and lists, dictionaries don't maintain any particular order of elements (though some modern implementations do preserve insertion order).

Conclusion

Understanding these four fundamental data structures - arrays, lists, stacks, and dictionaries - gives you a powerful toolkit for organizing and manipulating data in your programs. Arrays provide fast, indexed access to fixed-size collections. Lists offer the flexibility to grow and shrink dynamically. Stacks give you LIFO behavior perfect for managing sequential operations. Dictionaries enable fast lookups using meaningful keys rather than numeric positions. Each structure has its strengths and ideal use cases, and choosing the right one for your specific problem will make your programs more efficient and easier to understand. As you continue your journey in computer science, you'll find these data structures appearing everywhere - from simple homework assignments to complex real-world applications! šŸš€

Study Notes

• Array: Fixed-size collection with indexed access (0-based indexing), fast retrieval by position, ideal for known data sizes

• List: Dynamic collection that can grow/shrink, supports insertion/deletion operations, perfect for variable-sized data

• Stack: LIFO (Last In, First Out) structure with push/pop operations, used for undo functions and function call management

• Dictionary: Key-value pairs for fast lookups using meaningful identifiers, keys must be unique, ideal for associations and mappings

• Array access time: Constant O(1) - same speed regardless of array size

• List operations: Adding to end is fast, inserting in middle requires shifting elements

• Stack operations: Push (add to top), Pop (remove from top), Peek (view top), isEmpty (check if empty)

• Dictionary lookup: Typically constant O(1) time regardless of dictionary size

• Memory usage: Arrays are most memory-efficient, dictionaries use more memory due to key storage

• Use arrays when: Size is known, need indexed access, memory efficiency is important

• Use lists when: Size varies, need to insert/remove elements frequently, flexibility is key

• Use stacks when: Need LIFO behavior, managing sequential operations, implementing undo functionality

• Use dictionaries when: Need fast lookups by meaningful keys, associating related data, building databases or caches

Practice Quiz

5 questions to test your understanding

Data Structures Basics — GCSE Computer Science | A-Warded