In [ ]:
tuple # Tuples are another important data type, pervasive in Python without you even knowing it (at first)
In [ ]:
1, 2, 3, 'a', 'b', 'c' # You're using tuples just by putting commas in between a bunch of values
In [ ]:
type((1, 2, 3, 'a', 'b', 'c')) # YOu can confirm this fact, but when you do you HAVE TO use the normally optional parenthesis.
In [ ]:
atuple = 1, 2, 3, 'a', 'b', 'c' # The fact you usually don't need the parenthesis leads to extremely PYTHONIC coding style.
atuple
In [ ]:
atuple = (1, 2, 3, 'a', 'b', 'c') # This is the same as doing this, a more official way to create a tuple.
atuple
In [ ]:
atuple = tuple((1, 2, 3, 'a', 'b', 'c')) # There's even more formal ways to create a tuple. But why would you?
atuple
In [ ]:
alist = list((1, 2, 3, 'a', 'b', 'c')) # You'll also learn about lists which use square brackets instead of parenthesis.
alist
In [ ]:
a, b, c = 1, 2, 3 # The comma trick usually used for tuples can ALSO be used to define multiple variables at once.
print(a)
print(b)
print(c)
In [ ]:
a = 'first', 'second', 'third' # Using a single variable name with comma seperated values makes a tuple.
a
In [ ]:
for x in a:
print(x)
[print(x) for x in a] # You can do many of the same things with a tuple as with a list.
In [ ]:
mutable = [0, 0, 0, 0] # But lists are made to be very dynamic and use LOTS of computer resources for tricks like this.
mutable[2] = 'foo'
mutable
In [ ]:
immutable = (0, 0, 0, 0) # Tuples are an immutable data-type, meaning when they're set, they stay that way (error intentional)
immutable[2] = 'foo'
In [ ]:
list_of_tuples = [(1, 2, 3), (4, 5, 6), (7, 8, 9)] # Tuples are particularly useful as the rows in row & column shapes.
for a_tuple in list_of_tuples:
print(a_tuple)
In [ ]:
a = 'first', 'second', 'third'
print(a)
print(*a) # Using an asterisk before a tuple-name sort of de-tuples it.
In [ ]:
def foo(*args):
for arg in args: # This is useful when making functions that support arbitrary numbers of parameters.
print(arg)
foo('first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'and', 'so', 'on') # But this gets ahead of ourselves.
In [ ]:
def show(arg):
print(arg) # We're normally taught first how functions usually take one input.
show('me')
In [ ]:
def show(arg1, arg2):
print(arg1, arg2) # We're normally taught first how functions usually take one input.
show('me', 'too') # Without the asterisk, you'd have go code the function to expect eacy separate argument.