list1 = [1,2,3,4] list2 = [1, "a", "c", 3, "d"] list3 = list1 + list2
def hello(): print "hi" l = [1, 2, hello]
l = [1, 2, hello] # hello refers to a variable name l2 = [1, 2, "hello"] # "hello" is a string
l = [1, 2, hello] print l[0] # prints 1 print l[1] # prints 2 # Tougher Examples: l[2]() # prints "hi" l[-1]() # prints "hi" print l[-2] # prints 2
l = [2, 4, 6, 8, 10] l[0:2] # [2,4] l[2:4] # [6,8] l[:2] # [2,4] l[2:] # [6,8,10] l[:] # [2, 4, 6, 8, 10]
a = "foo" a[0] # "f" a[1] # "o" a[:2] # "fo"
l = [2, 4, 6, 8, 10] l.append(12) # l is now [2, 4, 6, 8, 10, 12] len(l) # 6 l.remove(4) # l is now [2, 6, 8, 10, 12] a = l.pop() # l is now [6, 8, 10, 12], a is now 2 l.index(10) # 2 l += [10, 20, 30] # l is now [6, 8, 10, 12, 10, 20, 30] l.count(10) # 2 l.sort() # l is now [6, 8, 10, 10, 12, 20, 30] l.reverse() # l is now [30, 20, 12, 10, 10, 8, 6]
array = ['A','dead','parrot'] delim = '.' str1 = delim.join(array) #str1 is 'A.dead.parrot' str2 = ' '.join(array) #str2 is 'A dead parrot'
from random import shuffle l = [1,2,3,4] shuffle(l)
l = [1,2,3,4,5] squares = [x**2 for x in l] # [1, 4, 9, 16, 25] even_squares = [x**2 for x in l if x % 2 == 0] # [4, 16]
Tuples are immutable lists:
list1 = [1, 2, 3, 4] list1.append(5) tuple1 = (1, 2, 3, 4) tuple1.append(5) # error
l = [1,2,3,4,5] squares = [] for x in l: squares.append(x**2)
squares = [1, 4, 9, 16, 25] for i in range(len(squares)): print "the element at index", i, "is", squares[i] for i, x in enumerate(squares): print "the element at index", i, "is", x
L1 = [1,2,3,4] L2 = [5,6,7,8] L3 = zip(L1,L2) # L3 is now [ (1,5) , (2,6) , (3,7) , (4,8) ] # Processing both sequences simultaneously in a for loop: for (x,y) in zip(L1,L2): print x + y, # prints out: 6 8 10 12