Introduction to Computer Science/5.6 Power Tools for Lists

5.6 Power Tools for Lists

🎯 Learning Goals for This Page
  • Use the len() function to find the number of items in a list.
  • Use the .sort() method to sort a list in place.
  • Use the .pop() method to remove an item by its index and get its value back.

Power Tools for Managing Lists

Python includes many built-in tools to make common list operations simple and fast. Today we'll look at one crucial function and a few powerful "methods" that belong to all lists.

Finding the Length with len()

The len() function is a simple but essential tool. It takes a list as an argument and returns the number of items currently in that list.

players = ["Alice", "Bob", "Charlie", "Diana"]
num_players = len(players)
print(f"There are {num_players} players on the team.") # Output: There are 4 players on the team.

Sorting a List with .sort()

The .sort() method sorts the items in a list alphabetically or numerically. Important: this method modifies the list in-place, meaning it permanently changes the original list's order.

scores = [92, 85, 100, 78]
scores.sort()
print(scores) # Output: [78, 85, 92, 100]

Removing and Getting an Item with .pop()

The .pop() method is a powerful way to remove an item. It does two things at once: it removes an item from a specific index, and it returns that item so you can use it. If you don't provide an index, it will remove and return the last item in the list.

players = ["Alice", "Bob", "Charlie"]
last_player = players.pop() # Pop the last item
print(f"We removed: {last_player}") # Output: We removed: Charlie
print(f"The list is now: {players}") # Output: The list is now: ['Alice', 'Bob']


Knowledge Check: Match the Tool to the Job

Can you remember the job of each tool? Try this quick matching game.

Note

Live Example: Managing a Deck of Cards

This Trinket demonstrates all these tools in action. Run it, then follow the "Your Turn" instructions to experiment with the code.

Python 3Initializing...
Loading code editor...
Program output will appear here...

Interactive Sandbox

Use this space to practice writing code and complete the "Your Turn" activities above.

Python 3Initializing...
Loading code editor...
Program output will appear here...