# A tuple
x = ("Paris Hilton", 1981)
type(x)
# You can address the members of a tuple using indices
x[0]
# A tuple of length one is specified like this
x = (1,)
# Note x is not a tuple here, as the interpretor just simplifies out the brackets
x = (1)
# Slicing works just like with strings:
x = ("a", "sequence", "of", "strings")
x[1:]
def quotient_and_remainder (x, y):
q = x // y
r = x % y
return (q, r)
(quot, rem) = quotient_and_remainder (4, 5)
julia = ("Julia", "Roberts", 1967, "Duplicity", 2009, "Actress", "Atlanta, Georgia")
len(julia) # The length of the tuple
x = ("a", "sequence", "of", "strings")
x[0] = "the" # Error
# To make edited tuples from existing tuples you therefore slice and dice them
print(("the",) + x[1:])
# Like strings we can do search in tuples using the in operator:
5 in (1, 2, 3, 4, 5, 6)
5 not in (1, 2, 3, 4, 5, 6)
L = [2, 1, 3]
L[1] = 5
a = 1
b = a
print(a)
print(b)
warm = ['red', 'yellow', 'orange']
hot = warm
hot.append('pink')
print(hot)
print(warm)
cool = ['blue', 'green', 'gray']
chill = cool[:]
chill.append('black')
print(chill)
print(cool)
chill = cool[:]
warm = ['yellow', 'orange']
hot = ['red']
brightcolors = []
brightcolors.append(warm)
brightcolors.append(hot)
print(brightcolors)
# [['yellow', 'orange'], ['red']]
hot.append('pink')
print(hot)
# ['red', 'pink']
print(brightcolors)
# [['yellow', 'orange'], ['red', 'pink']]
x = [ "a", 1, 2, "list"]
# Makes a new list, l, containing only the strings in x
l = [ i for i in x if type(i) == str ]
# The basic structure is:
# [ EXPRESSION1 for x in ITERABLE (optionally) if EXPRESSION2 ]
# it is equivalent to writing:
# l = []
# for x in ITERABLE:
# if EXPRESSION2:
# l.append(EXPRESSION1)
What's the difference between list(range(100)) and range(100)
A range, or iterable object, is a promise to produce a sequence when asked.
Why not just make a list? MEMORY
# This requires only the memory for j, i and the Python system
# Compute the sum of integers from 1 (inclusive) to 100 (exclusive)
j = 0
for i in range(100):
j += i
print(j)
# Alternatively, this requires memory for j, i and the list of 100 integers:
j = 0
for i in list(range(100)):
j += i
print(j)
With return you exit a function completely, possibly returning a value. The internal state of the function is lost.
Yield is like return, in that you return a value from the function and temporarily the function exits, however, the state of the function is not lost, and the function can be resumed to return more values.
This allows a function to act like an iterator over a sequence, where the function incrementally yields values, one for each successive resumption of the function