SORTING
>>> xs = [20,30,10,60,40]
>>> ss = sorted(xs)
>>> ss
[10, 20, 30, 40, 60]
>>> xs = [20,30,10,60,40]
>>> xs.sort()
>>> xs
[10, 20, 30, 40, 60]
>>> xs = ["Bob", "Alice", "Charles", "Fred", "George"]
>>> ss = sorted(xs)
>>> ss
['Alice', 'Bob', 'Charles', 'Fred', 'George']
>>> xs
['Bob', 'Alice', 'Charles', 'Fred', 'George']
>>> xs.sort()
>>> xs
['Alice', 'Bob', 'Charles', 'Fred', 'George']
>>>
>>> xs.sort(reverse=True)
>>> xs
['George', 'Fred', 'Charles', 'Bob', 'Alice']
>>> xs = [20,30,10,60,40]
>>> ss = sorted(xs,reverse=True)
>>> ss
[60, 40, 30, 20, 10]
>>>
>>> xs = [("a",20),("z",36),("p",11),("x",6)]
>>> sorted(xs)
[('a', 20), ('p', 11), ('x', 6), ('z', 36)]
>>> xs.sort(key=lambda x: x[1])
>>> xs
[('x', 6), ('p', 11), ('a', 20), ('z', 36)]
>>> xs.sort(key=lambda x: x[1])
>>> sorted(xs,key=lambda x: x[1])
[('x', 6), ('p', 11), ('a', 20), ('z', 36)]
>>> sorted(xs,key=lambda x: x[0])
[('a', 20), ('p', 11), ('x', 6), ('z', 36)]
>>>
WHILE LOOP
while True:
...
...
if C:
break
...
...
continue (skips remaining steps and re-performs loop)
while True:
x = input("Enter a command: ")
if x == 'q':
break
else:
print("You entered",x)
print("Done")
FORMATTED PRINT
>>> print("{:10s}{:5d}{:6.2f}".format("Charles",34,62.33))
Charles 34 62.33
>>> print("{:>10s}{:5d}{:6.2f}".format("Charles",34,62.33))
Charles 34 62.33
>>> print("{:>10s}{:>5d}{:6.2f}".format("Charles",34,62.33))
Charles 34 62.33
>>> print("{:>10s}{:<5d}{:6.2f}".format("Charles",34,62.33))
Charles34 62.33
>>> print("x{:10s}x{:5d}x{:6.2f}x".format("Charles",34,62.33))
xCharles x 34x 62.33x
>>>
< left-justified
> right-justified
^ centered
strings are left-justified by default
numbers are right-justified by default
ENUMERATED FOR-LOOP
>>> xs = ["John","Alice","Charles","Tom"]
>>> for (i,x) in enumerate(xs):
... print(i,x)
...
0 John
1 Alice
2 Charles
3 Tom
>>>
RANGE
for i in range(10):
print(i)
for u in range(5,10):
print(u)
for v in range(5,10,2):
print(v)
ZIP
for (x,y) in zip(xs,ys):
print(x,y)