a = [1, 2, 3, 4, 5]
a
[1, 2, 3, 4, 5]
a = list(range(1,6))
a
[1, 2, 3, 4, 5]
-l.append
-l.clear
-l.copy
-l.count
-l.extend
-l.index
-l.insert
-l.pop
-l.remove
-l.reverse
a.append(6)
a
[1, 2, 3, 4, 5, 6]
#note that .pop gives the one popped out, default is the last one, but you can give it a position to pop
a.pop()
6
a
[1, 2, 3, 4, 5]
a.append(6)
a.count(5)
1
max(a)
5
sum(a)
15
a.sort(reverse=True)
a
[5, 4, 3, 2, 1]
#let's get it back to what it was
a.sort()
a
[1, 2, 3, 4, 5]
a
[1, 2, 3, 4, 5]
copying without affecting the original list
b=a[:]
b
[1, 2, 3, 4, 5]
b.append(100)
b
[1, 2, 3, 4, 5, 100]
a
[1, 2, 3, 4, 5]
b==a
False
b=a
b.append(100)
b
[1, 2, 3, 4, 5, 100, 100, 100]
a
[1, 2, 3, 4, 5, 100, 100, 100]
b=a
b.append(100)
a
b=a
b.append(100)
a
b=a
b.append(100)
a
b=a
b.append(100)
a
b=a
b.append(100)
a
[1, 2, 3, 4, 5, 100, 100, 100, 100, 100]
a = [1, 2, 3, 4, 5]
b = [2, 2, 9, 0, 9]
def pick_the_larger(x,y):
result = [] # A list of the largest values
# Assume both lists are the same length
list_length = len(x)
for i in range(list_length):
result.append(max(x[i], y[i]))
return result
pick_the_larger(a,b)
[2, 2, 9, 4, 9]
map(some_function, some_iterable)
Faster performance: the less helper functions and the more language features
list(map(max, zip(a,b)))
[2, 2, 9, 4, 9]
[max(pair) for pair in zip(a,b)]
[2, 2, 9, 4, 9]
[max(ai,bi) for ai, bi in zip(a,b)]
[2, 2, 9, 4, 9]
# in this case, max works on iterable too
list(map(max,a,b))
[2, 2, 9, 4, 9]
[max(a[x],b[x]) for x in range(len(a))]
[2, 2, 9, 4, 9]