12  Python Lists: Creating Your Inventory

Today, we embark on a quest to master one of Python’s most powerful data structures: lists. Just as a knight needs an inventory to keep track of their possessions, Python uses lists to store and organize multiple items. Let’s uncover the world of Python lists and learn how to create, access, and perform basic operations on our digital inventories!

12.1 What is a List?

In Python, a list is a collection of items, much like a backpack in an adventure game. It can hold various types of items (strings, numbers, even other lists!) and keeps them in a specific order. Lists are incredibly versatile and are used in almost every Python program.

12.2 Creating a List

To create a list in Python, we use square brackets [] and separate the items with commas. Let’s create a simple inventory for our adventure:

inventory = ["sword", "shield", "health potion", "map"]
print(inventory)

This will output:

['sword', 'shield', 'health potion', 'map']

Congratulations! You’ve just created your first Python list.

Lists can contain different types of data:

hero_stats = ["Parzival", 100, True, 3.14]
print(hero_stats)

Output:

['Parzival', 100, True, 3.14]

Here, we have a string (name), an integer (health points), a boolean (is_alive), and a float (pi) all in one list!

12.3 Accessing List Elements

Now that we have our inventory, how do we check what’s inside? In Python, we can access list elements using their index. Remember, Python uses zero-based indexing, which means the first item is at index 0, the second at index 1, and so on.

Let’s access some items from our inventory:

inventory = ["sword", "shield", "health potion", "map"]

print(inventory[0])  # First item
print(inventory[2])  # Third item

Output:

sword
health potion

Think of indices like the pockets in your backpack. The first pocket (index 0) contains your sword, the third pocket (index 2) contains your health potion.

12.4 Negative Indexing

Python also allows negative indexing, which starts from the end of the list. The last item is at index -1, the second-to-last at -2, and so on.

print(inventory[-1])  # Last item
print(inventory[-3])  # Third-to-last item

Output:

map
shield

12.5 Getting the Length of a List

To find out how many items are in your inventory, you can use the len() function:

inventory_size = len(inventory)
print(f"You are carrying {inventory_size} items.")

Output:

You are carrying 4 items.

The len() function is incredibly useful when you need to know the size of your list, especially in loops or conditions.

12.6 Checking if an Item is in the List

Sometimes, you need to know if a specific item is in your inventory. Python makes this easy with the in keyword:

if "sword" in inventory:
  print("Sword is in inventory")
else:
  print("No sword in inventory")

…or another way…

has_sword = "sword" in inventory
has_bow = "bow" in inventory

print(f"Do you have a sword? {has_sword}")
print(f"Do you have a bow? {has_bow}")

Output:

Do you have a sword? True
Do you have a bow? False

This is incredibly useful for quick checks without needing to search through the entire list manually.

12.7 Changing List Elements

Unlike strings, lists are mutable, meaning we can change their elements after creating them. Let’s upgrade our sword:

inventory[0] = "magic sword"
print(inventory)

Output:

['magic sword', 'shield', 'health potion', 'map']

12.8 Practice Time: Manage Your Inventory

Now it’s your turn to create and manage your own inventory. Complete these quests:

  1. Create a list called magic_spells with at least 5 spell names.
  2. Print the first and last spell in your list.
  3. Replace the third spell with a new, more powerful spell.
  4. Print the total number of spells you know.
  5. Check if “fireball” is in your list of spells.

Here’s a starting point for your quest:

# Quest 1: Create your spell list
magic_spells = ["fireball", "ice shard", "lightning bolt", "heal", "invisibility"]

# Quest 2: Print first and last spell
# Your code here

# Quest 3: Replace the third spell
# Your code here

# Quest 4: Print total number of spells
# Your code here

# Quest 5: Check for "fireball" spell
# Your code here

12.9 Common Bugs to Watch Out For

As you experiment with lists, be wary of these common pitfalls:

  1. Index out of range: Trying to access an index that doesn’t exist will raise an IndexError. Remember, if a list has 4 items, the valid indices are 0, 1, 2, and 3.

    inventory = ["sword", "shield", "potion"]
    print(inventory[3])  # IndexError: list index out of range
  2. Forgetting that indexing starts at 0: The first element is at index 0, not 1.

  3. Case sensitivity with in: The in keyword is case-sensitive for strings.

    "Sword" in inventory  # This might be False even if "sword" is in the list

12.10 Conclusion and Further Resources

You’ve now learned how to create lists, access their elements, check for item existence, get list length, and modify list contents. These skills will be crucial as you continue your Python journey, allowing you to organize and manipulate data with ease.

To further enhance your list manipulation skills, check out these excellent resources:

  1. Python Official Documentation on Lists - The official Python guide to lists.
  2. Real Python’s Python Lists and Tuples - An in-depth tutorial on Python lists.
  3. W3Schools Python Lists - Interactive examples and exercises to practice list operations.

Remember, mastering lists is like learning to manage your inventory in a grand adventure. Keep practicing, and soon you’ll be wielding the power of Python lists like a true coding wizard! In our next lesson, we’ll explore more advanced list operations, including methods for modifying lists. Until then, may your inventories be ever organized and your code bug-free!