-4
file = ('cropdata.txt') 

I am not really sure what a tuple is. Here is file a tuple? How do tuples differ from lists or strings?

0.5772156649
  • 111
  • 1

1 Answers1

6

No, file is a string. If you're creating a tuple from individual objects, they always need to be separated by commas. This includes tuples with only a single object (put the comma after the item) because otherwise, the interpreter will use the parenthesis to group the expression for order of operations.

this_is_a_tuple = ('cropdata.txt',)  # Parenthesis are used for Order-of-operations grouping
this_is_a_string = ('cropdata.txt')  # Notice, no comma.
this_is_also_a_tuple = 'cropdata.txt',

However, an empty tuple is created with empty parenthesis:

this_is_an_empty_tuple = ()  # Look mom, no comma!

As for what a tuple is -- it's simply an object that holds references to other objects. The other objects can be looked up by index:

my_tuple = ('foo', 2)
my_tuple[0]  # foo
my_tuple[1]  # 2

Tuples are also iterable:

for item in my_tuple:
    ...

If you're familiar with list objects, tuple are very similar. The key difference is that a tuple is immutable -- Once created, you can't change the tuple (though you might be able to change objects that the tuple holds). The benefits of immutability (and related hashability) are a bit beyond the scope of this question and are answered really well elsewhere... For further discussion, see this question or this question.

Community
  • 1
  • 1
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • To add, tuples are immutable while lists can be modified. For instance, you couldn't say my_tuple[0] = 'somethingelse' but you could if it was a list. – Brian Schlenker Apr 18 '16 at 16:43
  • @BrianSchlenker -- Yep, I was just adding that in. – mgilson Apr 18 '16 at 16:44
  • You might consider changing "If you're creating a tuple from individual objects" to "If you're creating a tuple _with only a single object in it_" the way you have it doesn't make sense to me. – Tadhg McDonald-Jensen Apr 18 '16 at 16:48
  • @TadhgMcDonald-Jensen -- Mostly I was trying to cut out the case of `tuple(some_iterable)` ... But what I have is technically wrong because `()` is the way that an empty tuple is created ... – mgilson Apr 18 '16 at 16:50
  • "A tuple literal with a single element requires a trailing comma" perhaps? nevermind, link to documentation is sufficient. – Tadhg McDonald-Jensen Apr 18 '16 at 16:53