Skip to content
AL-306 · Computer Workshop/Introduction to Python-I/Quick Revision Short Notes

Computer Workshop/Introduction to Python-I (AL-306) - Unit 2 Short Notes

How unit 2 is examined

This unit covers Python's built-in collections (list, tuple, dictionary, set), the pandas DataFrame, and indexing and slicing; no question was asked recently, so every topic is taught briefly but completely.

Data Structure: List

<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>

Definition. <mark>A list is an ordered, mutable collection of items written in square brackets, such as [10, 20, 30].</mark>

Key points.

  1. A list keeps insertion order, allows duplicate values, and can mix data types such as [1, "a", 2.5].
  2. Lists are mutable, so an item can be changed in place: a[0] = 99.
  3. append(x) adds at the end, insert(i, x) adds at position i, extend(list2) joins another list, and remove(x) deletes the first match.
  4. pop() removes and returns the last item, sort() orders the list in place, and reverse() reverses it.
  5. len(a), min(a), max(a), sum(a) and x in a work on lists, and + joins while * repeats them.
  6. A list comprehension builds a list in one line: [x*x for x in range(4)] gives [0, 1, 4, 9].
a = [3, 1, 2]
a.append(5); a.sort()
print(a)  # [1, 2, 3, 5]

Tuples

<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>

Definition. <mark>A tuple is an ordered, immutable collection of items written in round brackets, such as (1, 2, 3).</mark>

Key points.

  1. Items cannot be changed, added or removed after creation, so t[0] = 5 raises TypeError.
  2. A single-item tuple needs a trailing comma: (5,) is a tuple but (5) is just an integer.
  3. Tuples are faster and use less memory than lists, so they suit fixed data such as coordinates or days of the week.
  4. Because they are immutable and hashable, tuples can be used as dictionary keys; lists cannot.
  5. Indexing, slicing, len(), +, *, count() and index() work as in lists: (1,2,2).count(2) is 2.
  6. Tuple packing and unpacking allow x, y = (1, 2), which is also how a function returns several values.
t = (1, 2, 3)
print(t[1:], len((5,)))  # (2, 3) 1

Example. A tuple can hold a list, whose contents can still change even though the tuple itself cannot: t = (1, [2, 3]); t[1].append(4) gives (1, [2, 3, 4]), but t[0] = 9 fails. To edit a tuple, convert it with list(t), change the list, and convert back with tuple().

Point List Tuple
Brackets [ ] ( )
Mutable Yes No
Speed and memory Slower, more memory Faster, less memory
Use as dictionary key No Yes
Methods Many (append, sort, pop) Only count, index
Typical use Data that changes Fixed records

Dictionary

<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>

Definition. <mark>A dictionary is a mutable collection of key-value pairs written in curly brackets, such as {'a': 1, 'b': 2}.</mark>

Key points.

  1. Each value is reached through its unique key, not by position, and a repeated key keeps only the latest value.
  2. Keys must be immutable (string, number or tuple), while values can be of any type.
  3. d['c'] = 3 adds a new pair or updates an existing one, and del d['a'] or d.pop('a') removes a pair.
  4. keys(), values() and items() return the keys, the values and the (key, value) pairs.
  5. d.get(key, default) returns the default instead of raising KeyError when the key is missing, while d['missing'] raises it.
  6. Looping with for k, v in d.items(): visits every pair, and key in d tests for a key.
d = {'a': 1}
d['b'] = 2
print(d.get('c', 0), list(d.keys()))  # 0 ['a', 'b']

Example. A student record: st = {'name': 'Ravi', 'roll': 12, 'marks': [70, 80]}. Then st['name'] gives 'Ravi', st['city'] = 'Bhopal' adds a pair, st.pop('roll') removes and returns 12, and len(st) counts the pairs. The update() method merges another dictionary, overwriting equal keys, and clear() empties the dictionary.

Pitfall. Writing d['missing'] raises KeyError; use get() or test key in d first.

DataFrame and Sets

<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>

Definition. <mark>A set is an unordered collection of unique items written in curly brackets, and a pandas DataFrame is a two-dimensional labelled table of rows and columns.</mark>

Key points.

  1. A set removes duplicates automatically, has no index or order, and holds only immutable items: set([1,1,2]) gives {1, 2}.
  2. An empty set is made with set(), because {} creates an empty dictionary.
  3. Set operators are union |, intersection &, difference - and symmetric difference ^: {1,2,3} & {2,3,4} gives {2, 3}.
  4. add(x) inserts, remove(x) deletes (error if absent), discard(x) deletes quietly, and <= tests a subset.
  5. A DataFrame is created with pandas.DataFrame(data), usually from a dictionary of columns or a CSV file read with pd.read_csv().
  6. Each column of a DataFrame can hold a different data type, and rows and columns carry labels (the index and the column names).
  7. df['name'] selects a column, df.loc[label] selects by label, df.iloc[position] selects by position, and head() and describe() inspect the data.
s = {1, 2, 3} | {3, 4}
print(s)  # {1, 2, 3, 4}

Example. Building a DataFrame and selecting from it:

import pandas as pd
df = pd.DataFrame({'name': ['A', 'B'], 'marks': [70, 80]})
print(df['marks'].mean())  # 75.0
print(df.iloc[0]['name'])  # A

The columns are name and marks, the row labels default to 0 and 1, and df.shape gives (2, 2). New columns are added by assignment, such as df['pass'] = df['marks'] > 75.

Point Set DataFrame
Type Built-in collection pandas table (library)
Order Unordered Rows and columns labelled and ordered
Duplicates Not allowed Allowed
Dimensions One Two

Constructing, indexing, slicing and content manipulation

<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>

Definition. <mark>Indexing picks one item by position, and slicing seq[start:stop:step] picks a range of items, excluding the stop position.</mark>

Key points.

  1. Collections are constructed with literals ([], (), {}) or with the constructors list(), tuple(), set() and dict(), which also convert one type to another.
  2. Indexes start at 0, and negative indexes count from the end, so a[-1] is the last item; an index beyond the length raises IndexError.
  3. In a[1:3] the start is included and the stop is excluded, so it gives items 1 and 2, and omitted bounds default to the ends.
  4. The step sets the stride, so a[::2] takes every second item and a[::-1] reverses the sequence.
  5. A slice of a list can be assigned to change its content: b = [1,2,3,4,5]; b[1:3] = [9] gives [1, 9, 4, 5].
  6. del b[0] removes an item, and after that deletion [1, 9, 4, 5] becomes [9, 4, 5].
  7. Slicing works on lists, tuples and strings, but a tuple or string slice makes a new object because these cannot be edited.
a = [10, 20, 30]; a.append(40)
print(a[1:3], a[-1], a[::-1])  # [20, 30] 40 [40, 30, 20, 10]

Example. Slicing a string and a tuple: "python"[1:4] gives 'yth', and (10,20,30,40)[::2] gives (10, 30). Slicing never raises an error for out-of-range bounds: [1,2,3][1:10] gives [2, 3].

Steps. To manipulate a list's content in the exam, follow this order: create the list, index or slice to read, assign to an index or slice to change, use append or insert to add, use remove, pop or del to delete, and finally sort or reverse to reorder.

Operation Syntax Result for a = [1,2,3,4]
Read one item a[2] 3
Read a range a[1:3] [2, 3]
Change an item a[0] = 7 [7, 2, 3, 4]
Insert a.insert(1, 8) [1, 8, 2, 3, 4]
Delete by value a.remove(3) [1, 2, 4]
Delete by index del a[0] [2, 3, 4]

Last-minute revision

  • A list is ordered and mutable and is written in []; a tuple is ordered and immutable and is written in ().
  • (5,) is a tuple, but (5) is an integer.
  • A dictionary holds key-value pairs in {}; keys are unique and immutable, and values can be anything.
  • d.get(k, default) avoids KeyError.
  • A set is unordered and unique; {} is an empty dictionary and set() is an empty set.
  • Set operators are | union, & intersection, - difference and ^ symmetric difference.
  • A DataFrame is a 2-D labelled table from pandas; loc selects by label and iloc by position.
  • A slice seq[start:stop:step] excludes stop, and [::-1] reverses.
  • The negative index -1 is the last item, and indexes start at 0.
  • Lists and dictionaries are mutable; tuples, strings and set items are immutable.
  • append adds one item and extend adds many; pop removes and returns.

Memory hooks

  • Tuple is "tough": once made it cannot be changed.
  • List is "loose": items can be freely edited, added and removed.
  • A dictionary works like a phone book: the name (key) gives the number (value).
  • A set is a bag of unique marbles: no order and no repeats.
  • A slice stops before the stop index, like a fence post that is not counted.
  • Round brackets for tuple, square for list, curly for dictionary and set.

Coverage checklist

  • Data Structure: List: definition, mutability, methods and comprehension (no past questions).
  • Tuples: immutability, single-item comma, packing (no past questions).
  • Dictionary: key-value pairs, methods, get (no past questions).
  • DataFrame and Sets: set operators, DataFrame creation and selection (no past questions).
  • constructing, indexing, slicing and content manipulation: constructors, indexes, slices, slice assignment (no past questions).
Go to where you left off?

Quick Add to Notes

Save questions, your own notes and screenshots into notes filed by unit. It takes a free account.

Create free account

Have an account? Log in