Python Data Collections
List | Tuple | Set | Dictionary
Python has four built-in collection types for storing multiple items. Each has unique
characteristics:
Collection Ordered Changeable Duplicates Syntax
List ✓ ✓ ✓ [ ]
Tuple ✓ ✗ ✓ ( )
Set ✗ ✓ ✗ { }
Dictionary ✓* ✓ Keys: ✗ { : }
*Ordered from Python 3.7+
1. List
Ordered, changeable collection written with square brackets. Allows duplicates and mixed
types.
Creating Lists
1 # Creating lists
2 fruits = ['apple', 'banana', 'cherry']
3 numbers = [10, 20, 30, 40, 50]
4 mixed = [1, 'hello', 3.14, True]
5
6 printprint(fruits) # ['apple', 'banana', 'cherry']
7 printprint(numbers) # [10, 20, 30, 40, 50]
Accessing & Slicing
1 fruits = ['apple', 'banana', 'cherry', 'date']
2
3 # Indexing
4 printprint(fruits[0]) # apple (first)
5 printprint(fruits[-1]) # date (last)
6
7 # Slicing
8 printprint(fruits[1:3]) # ['banana', 'cherry']
9 printprint(fruits[::-1]) # ['date', 'cherry', 'banana', 'apple']
Adding & Removing
1 nums = [1, 2, 3]
2
3 [Link](4) # [1, 2, 3, 4]
4 [Link](1, 99) # [1, 99, 2, 3, 4]
5 [Link](99) # [1, 2, 3, 4]
6 [Link]() # removes last → [1, 2, 3]
7 [Link](0) # removes index 0 → [2, 3]
8
9 printprint(nums) # [2, 3]
Sorting
1 data = [5, 2, 8, 1, 9]
2
3 [Link]() # [1, 2, 5, 8, 9]
4 [Link](reverse=True) # [9, 8, 5, 2, 1]
5 [Link]() # [1, 2, 5, 8, 9]
6
7 # sorted() doesn't change original
8 original = [3, 1, 2]
9 new_list = sortedsorted(original)
10 printprint(original) # [3, 1, 2]
11 printprint(new_list) # [1, 2, 3]
List Comprehension
1 # Squares of even numbers 1-10
2 squares = [x**2 for x in rangerange(1, 11) if x % 2 == 0]
3 printprint(squares) # [4, 16, 36, 64, 100]
4
5 # Convert to uppercase
6 words = ['hello', 'world', 'python']
7 upper = [[Link]() for w in words]
8 printprint(upper) # ['HELLO', 'WORLD', 'PYTHON']
2. Tuple
Ordered, unchangeable collection written with parentheses. Faster than lists, ideal for fixed
data.
Creating Tuples
1 coords = (10, 20)
2 colors = ('red', 'green', 'blue')
3
4 # Single-element tuple needs trailing comma
5 single = (42,) # tuple
6 not_tuple = (42) # integer
7
8 printprint(typetype(single)) # <class 'tuple'>
9 printprint(typetype(not_tuple)) # <class 'int'>
Accessing Items
1 t = (10, 20, 30, 40, 50)
2
3 printprint(t[0]) # 10
4 printprint(t[-1]) # 50
5 printprint(t[1:4]) # (20, 30, 40)
Tuple Unpacking
1 # Assign tuple values to variables
2 point = (3, 7)
3 x, y = point
4 printprint(x, y) # 3 7
5
6 # Swap variables
7 a, b = 10, 20
8 a, b = b, a
9 printprint(a, b) # 20 10
10
11 # Collect remaining with *
12 first, *rest = (1, 2, 3, 4, 5)
13 printprint(first) # 1
14 printprint(rest) # [2, 3, 4, 5]
Tuple Methods
1 t = (1, 2, 3, 2, 2, 4, 1)
2
3 printprint([Link](2)) # 3
4 printprint([Link](3)) # 2
5
6 # Concatenation & repetition
7 t1 = (1, 2, 3)
8 t2 = (4, 5, 6)
9 printprint(t1 + t2) # (1, 2, 3, 4, 5, 6)
10 printprint(t1 * 2) # (1, 2, 3, 1, 2, 3)
3. Set
Unordered collection with no duplicates, written with curly braces. Ideal for unique items and
math operations.
Creating Sets
1 fruits = {'apple', 'banana', 'cherry'}
2
3 # Duplicates removed automatically
4 nums = setset([1, 2, 2, 3, 3, 3, 4])
5 printprint(nums) # {1, 2, 3, 4}
6
7 # Empty set — use set(), not {}
8 empty = setset() # correct
9 not_set = {} # creates dictionary!
Adding & Removing
1 s = {1, 2, 3}
2
3 [Link](4) # {1, 2, 3, 4}
4 [Link](2) # no change, 2 exists
5 [Link](3) # removes 3, error if missing
6 [Link](99) # no error if missing
7
8 printprint(s) # {1, 2, 4}
Set Operations
1 A = {1, 2, 3, 4, 5}
2 B = {4, 5, 6, 7, 8}
3
4 printprint(A | B) # Union: {1, 2, 3, 4, 5, 6, 7, 8}
5 printprint(A & B) # Intersection: {4, 5}
6 printprint(A - B) # Difference: {1, 2, 3}
7 printprint(A ^ B) # Symmetric diff: {1, 2, 3, 6, 7, 8}
Common Use Case
1 # Remove duplicates from list
2 data = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
3 unique = listlist(setset(data))
4 printprint(unique) # duplicates removed (order varies)
4. Dictionary
Stores key-value pairs with unique keys. Ordered from Python 3.7+. Written with curly braces
and colons.
Creating Dictionaries
1 # Using curly braces
2 student = {
3 'name': 'Alice',
4 'age': 21,
5 'grade': 'A'
6 }
7
8 # Using dict()
9 person = dictdict(name='Bob', age=25, city='Delhi')
10
11 printprint(student['name']) # Alice
12 printprint(person['city']) # Delhi
Accessing & Modifying
1 student = {'name': 'Alice', 'age': 21, 'grade': 'A'}
2
3 # Access values
4 printprint(student['name']) # Alice
5 printprint([Link]('age')) # 21
6 printprint([Link]('marks', 0)) # 0 (default)
7
8 # Modify values
9 student['age'] = 22
10
11 # Add new key
12 student['city'] = 'Mumbai'
13
14 # Delete key
15 del student['grade']
16
17 printprint(student) # {'name': 'Alice', 'age': 22, 'city': 'Mumbai'}
Looping
1 inventory = {'apples': 50, 'bananas': 30, 'oranges': 20}
2
3 # Loop through keys
4 for item in [Link]():
5 printprint(item)
6
7 # Loop through values
8 for qty in [Link]():
9 printprint(qty)
10
11 # Loop through key-value pairs
12 for item, qty in [Link]():
13 printprint(f'{item} -> {qty}')
Common Methods
1 scores = {'Alice': 90, 'Bob': 85}
2
3 # pop() — remove and return
4 removed = [Link]('Bob')
5 printprint(removed) # 85
6
7 # update() — add or overwrite
8 [Link]({'Charlie': 78, 'Alice': 95})
9 printprint(scores) # {'Alice': 95, 'Charlie': 78}
10
11 # setdefault() — add only if missing
12 [Link]('Dave', 88) # adds Dave
13 [Link]('Alice', 0) # no change
14 printprint(scores['Alice']) # still 95
Nested Dictionary
1 employees = {
2 'emp1': {'name': 'Rahul', 'dept': 'IT', 'salary': 50000},
3 'emp2': {'name': 'Priya', 'dept': 'Finance', 'salary': 55000}
4 }
5
6 # Access nested values
7 printprint(employees['emp1']['name']) # Rahul
8 printprint(employees['emp2']['salary']) # 55000
9
10 # Loop through nested dict
11 for emp_id, info in [Link]():
12 printprint(f"{emp_id} -> {info['name']} | {info['dept']}")
Dictionary Comprehension
1 # Squares of 1 to 5
2 squares = {x: x**2 for x in rangerange(1, 6)}
3 printprint(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
4
5 # Filter students who scored 80+
6 scores = {'Alice': 95, 'Bob': 72, 'Charlie': 88, 'Dave': 60}
7 passed = {name: s for name, s in [Link]() if s >= 80}
8 printprint(passed) # {'Alice': 95, 'Charlie': 88}
5. Combined Example
Student record system using all four data types:
Full Program
1 # Student Record System
2 students = {} # dictionary to store records
3 departments = setset() # set for unique departments
4
5 def add_student(roll, name, dept, marks):
6 info = (name, dept) # tuple for fixed info
7 students[roll] = {
8 'info': info,
9 'marks': listlist(marks) # list for changeable marks
10 }
11 [Link](dept)
12
13 # Add students
14 add_student(101, 'Alice', 'CSE', [85, 90, 78])
15 add_student(102, 'Bob', 'ECE', [72, 68, 80])
16 add_student(103, 'Priya', 'CSE', [91, 88, 95])
17 add_student(104, 'Rahul', 'ME', [60, 74, 70])
18
19 # Display all students
20 printprint('--- All Students ---')
21 for roll, data in [Link]():
22 name, dept = data['info']
23 avg = sumsum(data['marks']) / lenlen(data['marks'])
24 printprint(f'Roll {roll}: {name} | {dept} | Avg: {avg:.1f}')
25
26 printprint('\nDepartments:', departments)
27
28 # Display top students
29 printprint('\n--- Top Students (avg >= 80) ---'Students (avg >= 80) ---')
30 for roll, data in [Link]():
31 name, dept = data['info']
32 avg = sumsum(data['marks']) / lenlen(data['marks'])
33 if avg >= 80:
34 printprint(f'{name} ({dept}) -> {avg:.1f}')
Quick Reference
Method Description
List
append(x) Add x to end
insert(i, x) Insert x at position i
remove(x) Remove first occurrence of x
pop(i) Remove and return item at index i
sort() Sort in ascending order
Tuple
count(x) Count occurrences of x
index(x) Find index of x
Set
add(x) Add x to set
remove(x) Remove x (error if missing)
discard(x) Remove x (no error)
union(s2) Combine sets (A | B)
intersection(s2 Items in both (A & B)
)
difference(s2) Items in A not B (A - B)
Dictionary
keys() Get all keys
values() Get all values
items() Get key-value pairs
get(key, Get value or default
default)
update(d2) Add/update from another dict
pop(key) Remove and return value