2

Basically, I have some variables and I want to quickly iterate through it.

I see three possibilities:

  • Using a list
  • Using a tuple
  • Using an implicit tuple

Respectively for example:

for regex in [regex_mail, regex_name]:
    ...

for regex in (regex_mail, regex_name):
    ...

for regex in regex_mail, regex_name:
    ...

Is there any reference indicating the syntax I should to use?
I looked at PEP8 but nothing is said about it.

I know this question may look as "primarily opinion based", but I am looking for concrete arguments that might allow me to choose the most adapted style (and PEP20 states that "There should be preferably only one way to do it").

Delgan
  • 18,571
  • 11
  • 90
  • 141
  • 2
    The second and third examples shown are exactly the same. The parentheses are only needed with a tuple on occasions where precedence demands it. The comma makes the tuple, not the brackets. Generally a tuple is more efficient than a list. – cdarke Sep 09 '17 at 19:00
  • Possible duplicate: https://stackoverflow.com/questions/6000291/best-style-for-iterating-over-a-small-number-of-items-in-python – andyhasit Sep 09 '17 at 19:09
  • 2
    My 2 cents: it doesn't matter very much. But the desire to iterate over named variables is often a code smell: it indicates that the data might belong in a collection data structure (or iterable object) that is given a meaningful name, rather than in atomic variables. – FMc Sep 09 '17 at 19:12
  • 1
    Opinion: Ignore any micro-benchmarks, and use a list because the value is *conceptually* a list; it is homogeneous and its cardinality is not fundamentally important. I often find it's helpful to imagine a statically typed language for comparison - in Haskell you'd write this with a list as `traverse_ (\regex -> ...) [regex_mail, regex_name]` (and it'd take some effort with generics or lenses to do the same with a tuple). – Chris Martin Sep 09 '17 at 21:02

1 Answers1

2

First, any performance difference between the 3 syntaxes is probably negligible.

Then, this answer does a good job at describing the difference between lists and tuples:

Tuples are heterogeneous data structures (i.e., their entries have different meanings), while lists are homogeneous sequences. Tuples have structure, lists have order.

The usual example is a collection of GPS coordinates. Use a tuple to separate X, Y and Z, use a list to separate coordinates :

[(48.77, 9.18, 400), (48.77, 9.185, 405), (48.77, 9.19, 410)]

According to this philosophy, a list should be used in your case.

Eric Duminil
  • 52,989
  • 9
  • 71
  • 124