AmbifulWorksheets
Cheat sheet
CBSE · Class 12 · Computer Science

Python Revision

A revision of Class 11 Python: strings and slicing, string methods, and list, tuple and dictionary operations, traced to the exact output.

Key ideas

Remember

s = 'python's[1:4] = 'yth', s[-2:] = 'on', s[::2] = 'pto', s[::-1] = 'nohtyp'
String methods'a b c'.split() = ['a', 'b', 'c']; '#'.join(['x', 'y']) = 'x#y'
Case'my BOOK'.capitalize() = 'My book'; 'my BOOK'.title() = 'My Book'
ListsL.sort() gives None; sorted(L) is a new list; L.pop() gives the last item
Tuples(1, 2) * 2 = (1, 2, 1, 2); (7,) has one item
Dictionariesd.get('x', 0) gives 0 for a missing key

Watch out

Worked example

Trace this program. Give (a) the first line it prints (b) the second (c) the third.
s = 'candle kite forest river ladder'
words = s.split()
longest = ''
initials = ''
for w in words:
    if len(w) > len(longest):
        longest = w
    initials = initials + w[0].upper()
print(len(words))
print(longest)
print(initials)

Working: words: candle, kite, forest, river, ladder; the first longest word is kept because > is strict

Answer: (a) 5; (b) candle; (c) CKFRL