1

I am working on a app that uses lists and tuples interchangeably and I am having a hard time understanding 1) what's the community "Pythonic" way and 2) is it ok to use them interchangeably?

Examples:

val = "hello"
tmp = ("world", "hello")
val in tmp

tmp = ["world", "hello"]
val in tmp
dennismonsewicz
  • 25,132
  • 33
  • 116
  • 189

1 Answers1

4

No, tuples and lists should not be used interchangeably. Two reasons:

1) There's a very practical difference, lists are mutable and tuples aren't, so there's a whole bunch of methods, like append which do not exist on tuples.

2) tuples and lists represent something semantically different. This source does a good job laying this out.

Alex Gaynor
  • 14,353
  • 9
  • 63
  • 113
  • 1
    The best example of `2` I have is an ordered pair. If you're trying to describe a point on the 2D plane you'd use a tuple `(3, 4)`. If you used a list `[3, 4]`, it would imply you could add on to that in some meaningful way. What point does `[3, 4, 5]` represent on the 2D plane? What about `[3,4,5,6,7,8,9,10,"Eggs","Foo",lambda x: frobnicate(x)]` ? – Adam Smith May 06 '14 at 19:20
  • In layman's terms, a list is a set of things, and tuple is ONE THING with more than one attribute. – Adam Smith May 06 '14 at 19:25