...

/

Tuples, Lists, and Strings Tips

Tuples, Lists, and Strings Tips

Learn how to use tuples, lists, and strings-related tips to improve our code.

Python includes a strong collection of data types and data structures. We’ll revisit this phrase and its variations throughout this chapter. Choosing the appropriate representation for our data may be vital. In the best case, an incorrectly chosen data type may cause significant performance degradation. In the worst case, it may cause logical errors and lead to incorrect results.

This chapter provides tips about both traditional and“obscure data structures and types, including standard containers, counters, and various numbers. We’ll explore how to:

  • Work with complex numbers, rational numbers, and infinities
  • Easily create modules
  • Transform lists
  • Count items
  • Recognize the immutability of tuples

The chapter also includes suggestions about advanced class design (class attributes and customized object print-outs).

Construct a one-element tuple

Creating a one-element tuple is difficult. Let’s first try to make a one-element tuple similar to one-element lists and one-element sets:

Press + to interact
print(type([0]))
print(type({0}))
print(type((0)))

The result isn’t a tuple, but an integer number; the first and only element itself. That’s because parentheses in Python have several uses. They participate in creating a tuple (in cooperation with commas), define functions, define subclasses, invoke functions, and change the order of evaluation, to name a few. In the last example, the outer pair of parentheses invokes the function and the inner pair changes the order of evaluation!

To inform Python that a tuple is born, add a comma after the first element. It’s the comma that builds a tuple, not the parentheses.

Press + to interact
print(type((0,)))
a=0, # Just a comma!
print(type(a))

Perhaps even the inner parentheses are redundant. Can we eliminate them? Let’s calculate the length of a one-element tuple.

Press + to interact
print(len(0,))

The error is that the comma also has several uses. It creates tuples, but it also separates arguments in a function call and parameters in a function definition. In the example above, Python considered the second use and treated 0 as the first argument. We could potentially avoid one-element tuples. We can replace a one-element container that isn’t expandable with a single scalar variable.

Improve readability with raw strings

Raw strings are prefixed with the letters, r or R, outside of the quotation marks. Within a raw string, the escape character—backslash ‘’—doesn’t have a special meaning. It’s no longer an escape character, merely a backslash. All special compound characters, such as ...