Manipulating tuples
Let aTuple
be a tuple of tuples, such that the inner tuples are all
of type (int,string)
.
def get_data(aTuple): nums = () # empty tuple words = () for t in aTuple: nums = nums + (t[0],) #singleton tuple if t[1] not in words: words = words + (t[1],) #singleton tuple min_n = min(nums) max_n = max(nums) unique_words = len(words) return (min_n, max_n, unique_words)The
get_data
function identifies the minimum and the maximum
numbers in the constituent tuples, and also the number of unique words (strings)
in the constituent tuples.
[]
Indices and ordering
a_list = [] L = [2, 'a', 4, [1,2]] len(L) evaluates to 4 L[0] evaluates to 2 L[2]+1 evaluates to 5 L[3] evaluates to [1,2], another list! L[4] gives an error i = 2 L[i-1] evaluates to 'a' because L[1]='a'
Lists are mutable
L = [2, 1, 3] L[1] = 5After this, the list
L
is [2, 5, 3]
. Note that this is the same object! Thus, if before the assignment we had L -> [2,1,3]
, then after the assignment we have L -> [2,5,3]
(the object remains the same, i.e., it does not get copied, rather it is updated in its place).
Iterating over a list
total = 0 for i in range(len(L)): total += L[i] print total
total = 0 for i in L: total += i print totalLike strings, can iterate over list elements directly.
0
to len(L)-1
.
Operations on Lists - Add
L.append(element)
L = [2,1,3] L.append(5) #L is now [2,1,3,5]What is the "." (dot) in
L.append(5)
?
object_name.do_something()
extend
method) to give you a new list
L1 = [2,1,3] L2 = [4,5,6] L3 = L1 + L2 #L3 is [1,2,3,4,5,6]; L1,L2 unchanged
L.extend(some_list)
. This is different from the + operator.
L1 = [2,1,3] L2 = [4,5,6] L1.extend([0,6]) #mutated L1 to [2,1,3,0,6]
Operations on Lists - Remove
del(L[index])
.L.pop()
, returns the removed element.L.remove(element)
L = [2,1,3,6,3,7,0] # do below in order L.remove(2) #mutates L to [1,3,6,3,7,0] L.remove(3) #mutates L to [1,6,3,7,0] del(L[1]) #mutates L to [1,3,7,0] L.pop() #returns 0 and mutates L to [1,3,7]
Convert lists to strings and back
list(s)
, returns a list
with every character from s
an element in L
.s.split()
to a split a string on a character parameter, splits on spaces if called without a parameter.''.join(L)
to turn a list of characters into a
string, can give a character in quotes to add char between every element.
s = "I<3 cs" #s is a string
list(s) #returns ['I','<','3',' ','c','s']
s.split('<') #returns ['I', '3 cs']
L = ['a','b','c'] # L
is a list
''.join(L) #returns "abc"
'_'.join(L) #returns "a_b_c"
Other list operations
sort()
and sorted()
reverse()
L = [9,6,0,3] sorted(L) # returns sorted list, does not mutate L L.sort() # mutates L to [0,3,6,9] L.reverse() # mutates L to [9,6,3,0]