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?
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?
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.