Python Lists: A closer look
Lists are one of the first data structures that most people learn about in Python. Python’s lists are simple enough that you can introduce them to non-programmers as a way of talking about how programmers store arbitrary amounts of information in code. Despite their apparent simplicity, there’s a lot you can learn about Python by looking at how lists work, and what happens if you push them too far.
This series builds a deeper understanding of how lists work and what you can do with them. It also discusses a number of related data structures, and when you should consider using them instead of lists.
This series has 11 parts:
MP #2: What is a list? Why is a bookshelf a good metaphor for a list? Why is it easier to write loops in Python than in many other languages?
MP #3: What happens when you add an item to a list? What is a deque, and when should you consider using one? How much space does a list take up in memory?
MP #5: What is a comprehension? What is a generator expression?
MP #8: What does immutable mean? When should you use a tuple instead of a list? How is memory usage for a tuple different than memory usage for a list? This post features a short program simulating poker hands, using only lists at first and then a mix of lists and tuples.
MP #10: How do you profile Python code, so that your optimization efforts are focused on sections of code that can actually make a difference in the overall execution time?
MP #12: What is an array, and when should you consider using one? This post starts with a question about flipping coins, and builds a list-based solution. It then implements the same solution using an array.
MP #14: What is a set? This post looks at data from the annual Stack Overflow programmer survey, and uses a set to efficiently answer a simple question about the survey results.
MP #15: What happens when you pass a list as an argument to a function? How can you prevent a function from modifying the list you’re passing to it?
MP #17: Many people have been stung by an attempt to modify a list inside a simple for
loop. This post examines what happens when you try to remove unwanted items inside a for
loop, and what you should do instead.
MP #20: Why shouldn’t you use an empty list as a default argument in a function? How do you remove all occurrences of an item from a list? This post features code that models a dealer in a card game and several players. If we’re not careful, both players get all the cards that were dealt!
MP #21: What happens when you copy a list? What does the deepcopy()
function do? This post also includes a list of takeaways from the series as a whole.
If you have any questions about what you find in these posts, please feel free to leave a comment and I will be happy to respond.