Lists (Part 1): Introduction to lists, declaring and initializing lists
Following our exploration of combining loops and conditionals, this article kicks off a new series on Working with Collections, starting with an introduction to Python lists. This concept is essential for storing and manipulating groups of data and is a foundational element in modern Python development.
📚 Prerequisites
Before we begin, please ensure you have a solid grasp of the following concepts:
- Basic Python syntax (variables, data types)
- Understanding of what a variable is
🎯 Article Outline: What You'll Master
In this article, you will learn:
- ✅ Foundational Theory: The core principles of Python lists (ordered, mutable, allows duplicates).
- ✅ Core Implementation: How to declare and initialize lists in various ways.
- ✅ Practical Application: Building a simple "shopping list" application to see lists in action.
- ✅ Best Practices & Anti-Patterns: Writing clean, maintainable, and idiomatic Python code when working with lists.
🧠 Section 1: The Core Concepts of Python Lists
Before writing any code, it's crucial to understand the foundational theory. A Python list is a collection that is used to store multiple items in a single variable.
Key Principles:
- Ordered: Lists maintain the order of items as they are added. The first item you add will be at index 0, the second at index 1, and so on.
- Mutable: "Mutable" is a fancy word for "changeable." You can add, remove, or change items in a list after it has been created.
- Allows Duplicates: Since lists are ordered and items are accessed by their index, you can have multiple items with the same value in a list.
Think of a list like a grocery list on a piece of paper. You can add items, cross them off, change them, and the order matters.
💻 Section 2: Deep Dive - Implementation and Walkthrough
Now, let's translate theory into practice. We'll explore the different ways to create a list in Python.
2.1 - Your First Example: Creating Lists with Square Brackets []
The most common way to create a list is by placing comma-separated values inside square brackets [].
# CodeBlock1.py
# Creating an empty list and a list with initial values.
# An empty list
empty_list = []
print(f"An empty list: {empty_list}")
# A list of integers
numbers = [1, 2, 3, 4, 5]
print(f"A list of numbers: {numbers}")
# A list of strings
fruits = ["apple", "banana", "cherry"]
print(f"A list of fruits: {fruits}")
# A list with mixed data types
mixed_list = [1, "hello", 3.14, True]
print(f"A list with mixed data types: {mixed_list}")
Step-by-Step Code Breakdown:
empty_list = []: We create an empty list by using square brackets with nothing inside.numbers = [1, 2, 3, 4, 5]: We create a list of integers. Each item is separated by a comma.fruits = ["apple", "banana", "cherry"]: We create a list of strings.mixed_list = [1, "hello", 3.14, True]: This demonstrates that a single list can hold items of different data types.
2.2 - Connecting the Dots: Using the list() Constructor
You can also create a list using the built-in list() constructor. This is especially useful for creating a list from another iterable, like a string or a tuple.
# CodeBlock2.py
# Using the list() constructor.
# Creating an empty list
empty_list_constructor = list()
print(f"An empty list from constructor: {empty_list_constructor}")
# Creating a list from a string
string_to_list = list("Python")
print(f"A list from a string: {string_to_list}")
# Creating a list from a tuple
tuple_to_list = list((1, 2, 3))
print(f"A list from a tuple: {tuple_to_list}")
Walkthrough:
empty_list_constructor = list(): Callinglist()without any arguments creates an empty list, just like[].string_to_list = list("Python"): When you pass a string tolist(), it creates a list where each character of the string is an item.tuple_to_list = list((1, 2, 3)): This converts a tuple (another collection type we'll learn about later) into a list.
🛠️ Section 3: Project-Based Example: Simple Shopping List
It's time to apply our knowledge to a practical, real-world Python scenario. We will now build a simple shopping list application.
The Goal: The program will allow a user to create a shopping list and then display it.
The Plan:
- Create an empty list to store the shopping items.
- Use a loop to ask the user to enter items.
- The user can type "done" to finish adding items.
- Display the final shopping list.
# ProjectExample.py
# The full Python code for the mini-project.
shopping_list = []
while True:
item = input("Enter a shopping list item (or type 'done' to finish): ")
if item.lower() == 'done':
break
shopping_list.append(item)
print("\nHere is your shopping list:")
for i, shopping_item in enumerate(shopping_list, 1):
print(f"{i}. {shopping_item}")
Walkthrough:
shopping_list = []: We start by creating an empty list to hold our items.while True:: We create an infinite loop to continuously ask for input.item = input(...): We get an item from the user.if item.lower() == 'done': break: If the user types "done" (in any case), webreakout of the loop.shopping_list.append(item): We use theappend()method to add the new item to the end of our list. (We'll cover list methods in the next article!)for i, shopping_item in enumerate(shopping_list, 1):: We loop through the final list and useenumerateto get both the index (starting from 1) and the item to print a nicely formatted list.
✨ Section 6: Best Practices and Anti-Patterns in Python
Writing code that works is one thing; writing code that is clean, maintainable, and idiomatic Python is another.
Python Best Practices (Idiomatic Way):
- Do this (Clarity): Use clear and descriptive names for your lists (e.g.,
fruits,user_names,shopping_list). - And this (Consistency): When creating an empty list, the
[]literal is generally preferred overlist()as it is slightly faster and more common.
Anti-Patterns (What to Avoid in Python):
- Don't do this: Creating a list with a single type of data and then adding other types later if it's not necessary. While possible, it can make the code harder to reason about.
💡 Conclusion & Key Takeaways
Congratulations! You've just learned the fundamentals of one of Python's most important data structures. Lists are the workhorse of many Python programs.
Let's summarize the key Python takeaways:
- Lists are created with
[]orlist(). - They are ordered, mutable, and can contain duplicate items of different data types.
- They are perfect for storing a collection of related items.
Challenge Yourself (Python Edition): To solidify your understanding, modify the shopping list application to prevent duplicate items from being added.
➡️ Next Steps
You now have a powerful new concept in your Python toolkit. In the next article, "Lists (Part 2): List methods, slicing, and list comprehensions", we will build directly on these ideas to explore how to manipulate and work with lists.
Keep practicing, keep exploring, and enjoy your Python coding adventure!
Glossary (Python Terms)
- List: An ordered and mutable Python collection of items.
- Mutable: Means that the object can be changed after it is created.
- Iterable: An object capable of returning its members one at a time. Examples include lists, strings, and tuples.