0% found this document useful (0 votes)
19 views7 pages

Python Collections: Lists, Tuples, Dicts, Sets Guide

Python lists basic and advanced
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views7 pages

Python Collections: Lists, Tuples, Dicts, Sets Guide

Python lists basic and advanced
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Collections Full Guide

Lists, Tuples, Dictionaries, Sets — Beginner to Advanced. Colored examples, outputs and short
explanations. A4 printable.

Lists — Basics & Advanced

Create list & access


nums = [1, 2, 3, 4] print(nums[0]) print(nums[-1])
Output:

1
4

Explanation: Indexing works from 0. Negative index -1 gives last item.

Slicing
letters = ['a','b','c','d','e'] print(letters[1:4]) print(letters[:3])
print(letters[2:])
Output:

['b', 'c', 'd']


['a', 'b', 'c']
['c', 'd', 'e']

Explanation: Slicing returns a new list: [start:stop:step].

Append, Insert, Extend, Remove, Pop


lst = [1,2,3] [Link](4) [Link](1, 1.5) [Link]([5,6])
[Link](1.5) print([Link]()) print(lst)
Output:

6
[1, 2, 3, 4, 5]

Explanation: append adds single item; extend concatenates another iterable; insert places at index; remove
deletes first match; pop removes and returns last (or index).

Sort & Reverse


arr = [3,1,4,2] [Link]() print(arr) [Link]() print(arr)
Output:

[1, 2, 3, 4]
[4, 3, 2, 1]

Explanation: sort() sorts in place; reverse() reverses in place. Use sorted() to get a new sorted list.

Copy vs Assignment
a = [1,2,3] b = a c = [Link]() [Link](4) print(b) print(c)
Output:

[1, 2, 3, 4]
[1, 2, 3]

Explanation: b references same list; c is shallow copy. For nested lists use deepcopy.

List Comprehension (basic & with condition)


squares = [x*x for x in range(6)] evens = [x for x in range(10) if x%2==0]
print(squares) print(evens)
Output:

[0, 1, 4, 9, 16, 25]


[0, 2, 4, 6, 8]

Explanation: Comprehensions are concise and often faster than loops.

Nested lists & flatten


matrix = [[1,2],[3,4]] flat = [x for row in matrix for x in row]
print(flat)
Output:

[1, 2, 3, 4]

Explanation: Double loop in comprehension flattens nested lists.

Enumerate & Zip with lists


names = ['a','b'] ages = [20,30] for i, name in enumerate(names): print(i,
name) for n, a in zip(names, ages): print(n, a)
Output:

0 a
1 b
a 20
b 30

Explanation: enumerate gives index; zip pairs iterables.

Unpacking and swapping


a = [1,2] x, y = a x, y = y, x print(x, y)
Output:

2 1

Explanation: Unpack lists into variables; swap without temp variable.


Tuples — Basics & Advanced

Create tuples & immutability


t = (1,2,3) print(t[0]) # t[0]=5 # would raise TypeError
Output:

Explanation: Tuples are immutable — can't change elements once created.

Single element tuple


single = (5,) print(type(single)) not_tuple = (5) print(type(not_tuple))
Output:

<class 'tuple'>
<class 'int'>

Explanation: Comma is required for single-element tuple.

Unpacking and swap


t = (10, 20, 30) a, b, c = t print(a, b, c)
Output:

10 20 30

Explanation: Tuple unpacking assigns values to multiple variables.

Tuple as dict keys & memory


coords = (10,20) positions = {coords: 'start'} print(positions[coords])
Output:

start

Explanation: Tuples (immutable) can be used as dict keys; lists cannot.

Namedtuple (readable tuples)


from collections import namedtuple Point = namedtuple('Point', ['x','y'])
p = Point(1,2) print(p.x, p.y)
Output:

1 2

Explanation: namedtuple provides readable fields and tuple immutability.

Tuple packing & * operator


a = (1,2) b = (3,4) c = (*a, *b) print(c) head, *rest = [10,20,30]
print(head, rest)
Output:

(1, 2, 3, 4)
10 [20, 30]
Explanation: Use * to unpack iterables into tuples/lists and in assignments.
Dictionaries — Basics & Advanced

Create & access


d = {'name':'Ali', 'age':30} print(d['name']) print([Link]('job', 'N/A'))
Output:

Ali
N/A

Explanation: Use get(key, default) to avoid KeyError.

Setdefault & update


d = {} [Link]('count', 0) d['count'] += 1 print(d) other = {'x':1}
[Link](other) print(d)
Output:

{'count': 1}
{'count': 1, 'x': 1}

Explanation: setdefault sets a default if key missing; update merges another dict in place.

Looping keys, values, items


person = {'a':1,'b':2} for k in [Link](): print(k) for v in
[Link](): print(v) for k,v in [Link](): print(k,v)
Output:

a
b
1
2
a 1
b 2

Explanation: items() yields (key, value) pairs for easy unpacking.

Dictionary comprehension
squares = {x: x*x for x in range(5)} print(squares)
Output:

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Explanation: Comprehensions create dicts concisely.

Merging dicts (Python 3.9+)


a = {'x':1} b = {'y':2} c = a | b print(c) # in-place: a |= b
Output:

{'x': 1, 'y': 2}

Explanation: Use | to merge into new dict; |= merges in place.


Nested dicts & safe access
data = {'user': {'name':'Maya'}} print([Link]('user', {}).get('name')) #
safe without KeyError
Output:

Maya

Explanation: Chain get() to safely access nested dicts.

Fromkeys & dict constructor


keys = ['a','b'] print([Link](keys, 0)) print(dict(a=1, b=2))
Output:

{'a': 0, 'b': 0}
{'a': 1, 'b': 2}

Explanation: Convenient constructors to build dicts.


Sets — Basics & Advanced

Create & unique


s = {1,2,2,3} print(s) print(2 in s)
Output:

{1, 2, 3}
True

Explanation: Sets store unique items; membership is fast.

Add, Remove, Discard, Pop


s = {1,2} [Link](3) [Link](4) print(s) # [Link](4) would raise
KeyError print([Link]()) print(s)
Output:

{1, 2, 3}
1
{2, 3}

Explanation: discard doesn't raise if missing; pop removes arbitrary element.

Union, Intersection, Difference


a = {1,2,3} b = {3,4} print(a | b) print(a & b) print(a - b)
Output:

{1, 2, 3, 4}
{3}
{1, 2}

Explanation: Use |, &, - for union, intersection, difference.

Subset, Superset, Symmetric Difference


a = {1,2} b = {1,2,3} print([Link](b)) print([Link](a))
print(a.symmetric_difference(b))
Output:

True
True
{3}

Explanation: Useful set relations and symmetric difference.

Frozen set (immutable)


fs = frozenset([1,2,3]) print(type(fs))
Output:

<class 'frozenset'>

Explanation: frozenset is immutable and hashable (can be dict keys).

You might also like