Python Notes (Lists, Tuples, Sets, Dictionary)
1) Lists (ordered, mutable)
• Create & read:
lst = ['Sanjana', 'Xyz', 25000, 'Canada']
lst[0] # index
lst[1:3] # slice
lst[-1] # negative index
• Update & traverse:
lst[0] = 'Abc'
for x in lst: print(x)
• Core methods:
len(lst)
lst.count('Sanjana')
lst.append('Toronto') # add at end
lst.insert(1, 'Dev') # add at index
lst.extend(['NYC', True]) # add many
lst.remove('Toronto') # first match, ValueError if missing
lst.pop() # last item (or pop(i))
lst.clear()
lst.reverse() # in-place
lst.sort(key=str, reverse=True) # in-place; use key=...
sorted(lst, key=str) # returns new list
• Build from strings/range:
"sanjana is my name".split() # -> ['sanjana', 'is', 'my', 'name']
list(range(11)) # 0..10
• Comprehensions (fast & pythonic):
[x for x in range(10) if x % 2 == 0]
[x if x%2==0 else -x for x in range(5)] # with inline if/else
[w[0] for w in ['Sanjana','Xyz','Canada','Abc']]
2) Tuples (ordered, immutable)
• Create:
t = (20, 90, 87)
single = (10,) # the comma matters
tuple(range(5)) # typecast
Ops & functions:
t + (1, 2); (1, 2) * 2
len(t); t.count(20); t.index(90)
min(t); max(t)
sorted(t, reverse=True) # returns list
'a' not in t
• Packing / unpacking:
a, b = 10, 20
p = a, b # packing -> (10, 20)
x, y = p # unpacking
• Note: there’s no “tuple comprehension”; (expr for x in seq) is a generator expression.
Tuples are immutable, but they can hold mutable objects (e.g., a list). If that inner list changes,
the tuple’s contents effectively change.
3) Sets (unordered, unique elements)
• Properties: no duplicates, no indexing, very fast membership tests (O(1) average).
• Create & update:
s = {10, 20, 30}
s.add(40)
s.update([50, 60, 40]) # add many
s.copy()
s.pop() # removes an arbitrary element
s.remove(80) # KeyError if missing
s.discard(80) # no error if missing
s.clear()
• Set algebra:
x | y # union
x & y # intersection
x - y # difference
x ^ y # symmetric difference
x.issubset(y); x.issuperset(y); x.isdisjoint(y)
Also: frozenset (immutable set, hashable → can be keys in dicts).
Tip: To “index” a set, convert to a list first: list(s)[0] (order not guaranteed).
4) Dictionaries (key → value)
• Properties: unique keys, values can repeat, insertion order preserved (3.7+), mutable.
• Create & access:
d = {100: 'Sanjana', 200: 'Xyz', 300: 'Abc'}
d[100] # KeyError if missing
d.get(999) # -> None
d.get(999, 'default') # -> 'default'
100 in d # membership test on keys
Update & delete:
d[100] = 'Tushar'
del d[100]
d.clear()
• Methods you’ll actually use:
len(d)
d.keys() # dict_keys view (iterable, set-like)
d.values() # dict_values view
d.items() # (key, value) pairs
d.copy()
d.pop(300) # KeyError if missing
d.pop(300, 'fallback') # safe pop with default
d.popitem() # LIFO in CPython 3.7+
d.setdefault('k', 0) # get or set default
d.update({'a': 1})
• Comprehension & frequency map:
squares = {x: x*x for x in range(6)}
word = "mississauga"
freq = {}
for ch in word:
freq[ch] = freq.get(ch, 0) + 1
• Useful from collections:
from collections import defaultdict, Counter
dd = defaultdict(int) # auto-0 for missing keys
cnt = Counter(word) # frequency in one line
5) Ranges, Generators & Itertools
• range(0, n) is a lightweight, immutable sequence (not a list). Convert with list(range(n))
only if needed.
• Generators are lazy:
g = (x*x for x in range(10))
next(g)
• Check out itertools for pro-level loops: chain, islice, product, groupby, etc.
6) Sorting Like a Pro
people = [{'name':'Abc','age':28}, {'name':'Xyz','age':32}]
people.sort(key=lambda p: (p['age'], p['name'])) # in-place
sorted_people = sorted(people, key=lambda p: p['age']) # new list
• Remember: list.sort() mutates; sorted() returns a new list.
• reverse=True and key= are your best friends.
7) Bonus Tools You’ll Actually Use
• collections.deque → fast queue/stack with append, appendleft, popleft.
• namedtuple/dataclasses → lightweight records with readable fields.
• any() / all() / sum() on comprehensions for clean checks & aggregations.
• Slicing trick: lst[::-1] (reverse copy). Note: slicing creates a new list (O(n)).
Mini Practical Snippets
• Remove a batch of items from a list:
lst = ['Sanjana','Xyz',25000,'Canada','Abc',27.98,'true']
to_remove = {'true','Canada'} # set for O(1) membership
lst = [x for x in lst if x not in to_remove]
• First non-repeating char:
from collections import Counter
s = "swiss"
c = Counter(s)
next((ch for ch in s if c[ch]==1), None)