beginner

Python Lists Basics

Learn to create and manipulate lists, Python's most versatile data structure.

Lists are one of Python's most powerful and commonly used data structures. They allow you to store collections of items in a single variable, making it easy to organize and process data. From simple to-do apps to complex data analysis, lists are everywhere in Python programming. This exercise introduces you to creating lists, accessing elements, and performing basic list operations.

📚 Concepts & Theory

Creating Lists:

fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
empty = []

Accessing Elements (Indexing):

  • Indexing starts at 0

  • Negative indices count from the end

fruits[0]   # "apple"
fruits[-1] # "cherry" (last item)

Slicing:

fruits[0:2]  # ["apple", "banana"]
fruits[1:] # ["banana", "cherry"]
fruits[:2] # ["apple", "banana"]

Common List Methods:

  • append(item) - Add item to end

  • insert(index, item) - Insert at position

  • remove(item) - Remove first occurrence

  • pop() - Remove and return last item

  • len(list) - Get list length
Modifying Lists:
fruits.append("orange")  # Add to end
fruits[0] = "grape" # Replace first item
del fruits[1] # Delete by index

🎯 Your Challenge

Create a list called `colors` with three items: "red", "green", "blue". Then add "yellow" to the end of the list using the append method. Finally, access and store the first color in a variable called `first_color`.

📝 Starter Code

Python
# Create a list with 3 colors
colors = 

# Add "yellow" to the end


# Get the first color
first_color = 
  • Lists are created with square brackets []
  • Items are separated by commas
  • Use .append() to add items to the end
  • First element is at index 0, not 1

Solution

Python
colors = ["red", "green", "blue"]

colors.append("yellow")

first_color = colors[0]

Explanation

We create a list using square brackets with items separated by commas. The append() method adds an item to the end of the list, so our list becomes ["red", "green", "blue", "yellow"]. We access the first element using index 0 because Python uses zero-based indexing.

⚠️ Common Mistakes to Avoid

  • Using parentheses instead of square brackets for lists
  • Forgetting that indexing starts at 0
  • Using wrong method name (add instead of append)
  • Not putting strings in quotes inside the list

❓ Frequently Asked Questions

Yes! Python lists can contain any mix of data types including numbers, strings, booleans, and even other lists.
append() adds an item to the end of the list, while insert() adds an item at a specific position you specify.

🔗 Related Concepts