Python Lists: Storing Multiple Values in One Container

Lesson Overview

Learn about Python's list data type - a powerful way to store multiple values in a single variable. Understand why lists are essential for real-world programming, how to create and manipulate them, and master basic list operations with intuitive examples.

Lesson Content

Lists: A New Data Type for Collections

So far, we've learned about individual data types:

  • int: Stores one number (age = 25)
  • str: Stores one text value (name = "John")
  • bool: Stores one true/false value (is_student = True)

Individual data types work perfectly for storing single pieces of information, but imagine you're planning your birthday party and need to keep track of 20 guests' names - creating 20 separate variables like guest1, guest2, guest3... would be completely impractical and impossible to manage effectively. This is exactly where lists become essential, acting like a smart container that can hold multiple related values in a single variable at once.

Why Lists are Useful: Real-World Examples

Consider these everyday scenarios where you naturally group related items:

Shopping List Example

Instead of creating separate variables for each item in daily groceries list:

# Without lists - tedious and impractical
item1 = "milk"
item2 = "bread"
item3 = "eggs"
item4 = "apples"
item5 = "chicken"

You can use a single list:

# With lists - clean and organized
shopping_list = ["milk", "bread", "eggs", "apples", "chicken"]

More Real-World List Examples

  • Student grades: [85, 92, 78, 96, 88] - All grades in one place
  • Phone contacts: ["Mom", "Dad", "Best Friend", "Work"] - All contacts together
  • Website URLs: ["google.com", "facebook.com", "youtube.com"] - Related links

Benefits of using lists:

  • Organization: Keep related data together
  • Flexibility: Add or remove items as needed
  • Simplicity: One variable instead of many

Creating Lists in Python

Lists are created using square brackets [ ] with items separated by commas:

# Creating different types of lists
numbers = [1, 2, 3, 4, 5]                    # List of integers
names = ["Alice", "Bob", "Charlie"]          # List of strings  
grades = [85.5, 92.0, 78.5, 96.0]            # List of floats
flags = [True, False, True, False]           # List of booleans

# Mixed data types in one list
mixed = [25, "John", True, 85.5]            # Different Data types together

# Empty list
empty_list = []                             # No items yet

print(numbers)    # Output: [1, 2, 3, 4, 5]
print(names)      # Output: ['Alice', 'Bob', 'Charlie']
print(mixed)      # Output: [25, 'John', True, 85.5]

🚂List Indexing: Like Train Bogies with ID Numbers

Think of a Python list like a train with multiple bogies (compartments). Each bogie has an ID number attached to it - just like real trains have S1, S2, S3, etc.

Python's indexing works the same way - it assigns ID numbers to each item in your list so you can identify and find them easily. The only difference is that Python starts counting from 0 instead of 1, like having bogies numbered 0, 1, 2, 3...

When you want to access a specific item from your list, you use the square brackets [] with the ID number - just like telling the train conductor "bring me the passenger from bogie number S2." Python looks at that ID number and fetches exactly what's stored in that position.

Just like you can walk through a train from either the front engine to the last bogie or backward from the last bogie to the front, Python lists also allow you to access the item in both directions - regular indexing starts from position 0 at the beginning, while negative indexing starts from -1 at the end and counts backward, making it super easy to grab items from the tail end of your list without having to know exactly how long the list is.

Understanding List Indexing
# List with index positions shown
fruits = ["apple", "banana", "orange", "grape"]
#Index:    0        1         2        3

# Accessing individual items with index
print(fruits[0])    # Output: "apple"  (first item)
print(fruits[1])    # Output: "banana" (second item) 

#Negative Indexing
fruits = ["apple", "banana", "orange", "grape"]
#Negative: -4      -3         -2        -1

print(fruits[-1])   # Output: "grape"  (last item)
print(fruits[-2])   # Output: "orange" (second to last)

List Slicing: Getting Multiple Train Bogies at Once

Now that you understand how to get one specific bogie from your train using indexing, what if you want to get multiple bogies in a row? That's where list slicing comes in.

The beautiful part is that slicing gives you a new smaller train with just the bogies you wanted, while keeping the original train intact. This makes slicing perfect for getting the first few items, the last few items, or any chunk of data from the middle of your list​.

Syntax:

# start ==> Start Index
# end ==> End Index
list[start:end]

Slicing Code Snips

letters = ["a", "b", "c", "d", "e", "f", "g"]
#Index:     0    1    2    3    4    5    6    

# Basic slicing
print(letters[1:4])    # Output: ['b', 'c', 'd'] (index 1 to 3)
print(letters[0:3])    # Output: ['a', 'b', 'c'] (index 0 to 2)
print(letters[2:6])    # Output: ['c', 'd', 'e', 'f'] (index 2 to 5)

# Slicing shortcuts
print(letters[:3])     # Output: ['a', 'b', 'c'] (start to index 2)
print(letters[3:])     # Output: ['d', 'e', 'f', 'g'] (index 3 to end)
print(letters[:])      # Output: ['a', 'b', 'c', 'd', 'e', 'f', 'g'] (entire list)

# Negative slicing
print(letters[-3:])    # Output: ['e', 'f', 'g'] (last 3 items)
print(letters[:-2])    # Output: ['a', 'b', 'c', 'd', 'e'] (all except last 2)

Slicing will also work with String data-types, Try it out

Basic List Operations

Just like strings have helpful methods like upper() and lower(), lists also come with their own set of built-in operations that make working with collections super easy. Lets focus on few important ones.

MethodWhat It DoesHow It WorksExample Result
append()Adds item to the endLike adding a new bogie to the end of a train[1, 2, 3]-> [1, 2, 3, 4]
insert()Adds item at specific positionLike inserting a new bogie between existing ones[1, 3, 4] -> [1, 2, 3, 4]
remove()Removes first matching itemFinds and removes the item by its value[1, 2, 3, 2] -> [1, 3, 2]
pop()Removes item at position and returns itLike detaching a bogie and telling you what was in it[1, 2, 3] -> [1, 2](returns3)
len()Provides total length of the listcount of total bogies in the train[1, 2, 3, 5] -> 4 (total count of items)
sort()Sort the list based on itemsre-order the bogies based on the bogie Name/ID[3, 5, 1, 9] -> [1,3, 5,9]

List Operations code snips

#Initial Shopping List:
shopping_list = ["milk", "bread", "eggs"]    
print("Before:", shopping_list)                      # Before: ['milk', 'bread', 'eggs']
#Append 
shopping_list.append("apples")
print("After adding apples:", shopping_list)        # After adding apples: ['milk', 'bread', 'eggs', 'apples']  

#Insert
shopping_list.insert(1, "mango")                    # Insert at index 1( second position)
print("After inserting mango:", shopping_list)      # After inserting mango: ['milk','mango', 'bread', 'eggs', 'apples']  

#Remove
shopping_list.remove(1, "bread")
print("After removing bread:", shopping_list)      # After inserting mango: ['milk','mango', 'eggs', 'apples']  

#Pop
removed_item = shopping_list.pop(2) 
print("Removed item:", removed_item)               # Removed item: eggs
print("After pop() Operation: ", shopping_list)    # After pop() Operation:  ['milk','mango', 'apples']  

numbers = [64, 34, 25, 12, 22, 11, 90]
print("Original:", numbers)                        # Original: [64, 34, 25, 12, 22, 11, 90]

# Sort in ascending order
numbers.sort()
print("Sorted ascending:", numbers)                # Sorted ascending: [11, 12, 22, 25, 34, 64, 90]

# Reverse the current order
numbers.reverse()
print("Reversed:", numbers)                        # Reversed: [90, 64, 34, 25, 22, 12, 11]

List Concatenation: Combining Lists

Just like strings, you can combine (concatenate) lists using the + operator:

# Combining two lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list1 + list2
print(combined)  # Output: [1, 2, 3, 4, 5, 6]

Key Takeaways

  • Lists store multiple values in a single variable using square brackets [ ]
  • Zero-based indexing: First item is at index 0, second at index 1, etc.
  • Lists are mutable: You can change, add, and remove items after creation
  • append() adds items to the end, insert() adds at specific positions
  • remove() deletes by value, pop() deletes by index and returns the item
  • Slicing extracts portions of lists using list[start:end] syntax
  • Concatenation combines lists using the + operator

Coming Up Next

Excellent work! You now understand how to work with lists - Python's most versatile data structure for storing collections of related data. You've learned to create lists, access their contents, modify them, and perform useful operations.

In our next lesson, we'll explore Dictionaries - another powerful data structure that stores data in key-value pairs, perfect for organizing information like phone books, student records, and configuration settings.

You're building a strong foundation in data organization and manipulation!