# Sequences - lists, tuples, strings
# Tuples
# A sequence is a set of values stored
# as a single variable
# Thus we must modify our original definition
# of a variable:
#
# OLD: A variable is a name for a memory location
#
# NEW:
# A variable is a name for ONE OR MORE
# memory locations
#
#
# Creating a tuple:
# Empty tuple
T = ()
# With values
T = (123, 2.34)
# If there is only one value, special syntax:
T = (134, )
# Human language conflict: Ordinals
# Python, like many languages, starts counting at 0
# So the positions in a tuple are the "zeroth" position,
# then the "first" position, etc
# We will try to avoid ordinals - use the position number
T = (1, 3, 5, 7, 9)
# 1 is at position 0
# 3 is at position 1
# 5 is at position 2
# An "index" is a position within a sequence
# We use the index when we want to reference (use) a value
# in a sequence
T = (1, 3, 5, 7, 9)
x = T[0] # x contains: 1 because position 0 of T contains the value 1
y = T[5] # y contains: NOTHING - position 5 is out of bounds (ERROR)
# Note that () used for DEFINING the tuple
# But [] used for REFERENCING the tuple
# () Parentheses ("parens")
# [] Brackets ("square brackets")
# {} Braces ("curly braces")
# Hopefully clear that we need to know how long the tuple is:
# Use the len() function
length = len(T) # How many elements are in the tuple
# Last position will ALWAYS be:
last_pos = len(T) - 1
# Example
T = (1, 2, 6, 7, 43, 23, 4, 3)
# Add up the first and last value in the tuple
sum_begin_end = T[0] + T[len(T)-1]
# OR
pos = len(T) - 1
sum_begin_end = T[0] + T[pos]
# Which demonstrates the true power of sequences:
# We can use variables for the index
# Why must the index variable be an integer?
# "Can't have the 1.5th value"
# Just like range() -- actually, range()
# produces a sequence
# FOR loop:
for i in range(0, 10):
# Can also be written as:
for i in (0, 1, 2, 3, 4, 5, 6, 7, 8, 9):
# Can use an arbitrary sequence:
T = (2, 5, 32, 46, 89)
for i in T:
# Will step through the values in T
# Printing
print T
# Can also loop through the values
for x in T:
print x # will print the values individually
# Most of the time
for i in range(0, len(T)):
print T[i] # Gives value
# But now we know the index
# Tuples are IMMUTABLE
# Immutable = Not Changeable
# A tuple can contain any data type
# including other tuples, strings, etc
T = (1, 3.4, 'fred', (1, 2, 3))
# Note that (1, 2, 3) occupies a single
# position in T -- T[3]
x = T[3] # x will contain (1, 2, 3)
# Can reference this as:
y = x[2] # y contains 3
# Or
y = T[3][2] # same effect
# Save a value from a variable
a = 47
b = 39
T = (a, b) # contains (47, 39)
# Easy baby step:
# A string is like a tuple of characters
s = 'Fred'
# s is immutable
# The last letter in s is at position 3
# len(s) is the length of the string
# A string is NOT a tuple of characters
T = ('F', 'r', 'e', 'd')