Understanding When to Use Tuples Instead of Lists


At this point, you may be thinking, "Why use tuples at all?" It's true that lists can do everything tuples can, plus more. But don't be so quick to dismiss tuples. There is a place for them in your Python programming world. There are a few occasions where tuples make more sense than lists.

  • Tuples are faster than lists. Because the computer knows they won't change, tuples can be stored in a way that makes using them faster than using lists. For simple programs, this speed difference won't matter, but in more complex applications, with very large sequences of information, it could.

  • Tuples' immutability makes them perfect for creating constants since they can't change. Using tuples can add a level of safety and clarity to your code.

  • Sometimes tuples are required. In some cases, Python requires immutable values. Okay, you haven't actually seen any of those cases yet, but there is a common situation you'll see when you learn about dictionaries, later in this chapter. Dictionaries require immutable types, so tuples will be essential when creating some kinds of dictionaries.

But, because lists are so flexible, you're probably best off using them over tuples in most cases.




Python Programming for the Absolute Beginner
Python Programming for the Absolute Beginner, 3rd Edition
ISBN: 1435455002
EAN: 2147483647
Year: 2003
Pages: 194

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net