syntax Copy
t = (val1, val2, ...)
t = val1, val2example Copy
point = (10 , 20 )
singleton = (42 ,)
x, y = point
print (f"x={x}, y={y}" )
print (len(singleton))output
x=10, y=20
1Note A single-element tuple requires a trailing comma: (42,). Without it, (42) is just an integer in parentheses. Tuples are immutable.
create tuple single element tuple unpack tuple immutable sequence
syntax Copy
from collections import namedtuple
Point = namedtuple('Point' , ['x' , 'y' ])example Copy
from collections import namedtuple
Color = namedtuple("Color" , ["red" , "green" , "blue" ])
sky = Color(135 , 206 , 235 )
print (sky.red, sky.blue)
print (sky._asdict())output
135 235
{'red': 135, 'green': 206, 'blue': 235}Note Named tuples give readable field access while staying immutable. For mutable fields or defaults, consider dataclasses instead.
named tuple struct record type tuple with names
NamedTuple (typing-based) syntax Copy
from typing import NamedTuple
class Name(NamedTuple):
field: type example Copy
from typing import NamedTuple
class Endpoint(NamedTuple):
host: str
port: int = 443
api = Endpoint("api.example.com" )
print (api.host, api.port)output
api.example.com 443Note The class-based NamedTuple supports type annotations and default values, making it more modern than the functional namedtuple() form.
typed named tuple namedtuple class NamedTuple defaults
syntax Copy
s = {val1, val2, ...}
s = set(iterable)example Copy
tags = {"python" , "tutorial" , "beginner" }
from_list = set([1 , 2 , 2 , 3 , 3 , 3 ])
print (from_list)
empty_set = set()
print (type (empty_set))output
{1, 2, 3}
<class 'set'>Note Use set() for an empty set, NOT {}. Empty braces {} create an empty dictionary, not a set.
create set unique values remove duplicates empty set
syntax Copy
a | b (union)
a & b (intersection)
a - b (difference)
a ^ b (symmetric difference)example Copy
frontend = {"alice" , "bob" , "carol" }
backend = {"bob" , "carol" , "dave" }
print (frontend | backend)
print (frontend & backend)
print (frontend - backend)
print (frontend ^ backend)output
{'alice', 'bob', 'carol', 'dave'}
{'bob', 'carol'}
{'alice'}
{'alice', 'dave'}Note Set operations are extremely fast (O(min(len(a), len(b))) for intersection). Use them instead of nested loops for membership checks.
set union set intersection set difference compare sets venn diagram
frozenset (Immutable Set) syntax Copy
fs = frozenset(iterable)example Copy
permissions = frozenset(["read" , "write" ])
print ("read" in permissions)
cache = {permissions: "admin" }
print (cache[frozenset(["read" , "write" ])])output
True
adminNote frozenset is hashable, so it can be used as a dict key or as an element inside another set. Regular sets cannot.
frozenset immutable set hashable set set as key
syntax Copy
{expression for item in iterable if condition}example Copy
emails = ["[email protected] " , "[email protected] " , "[email protected] " , "[email protected] " ]
unique_lower = {e.lower() for e in emails}
print (unique_lower)output
{'[email protected] ', '[email protected] ', '[email protected] '}Note Set comprehensions automatically deduplicate results. Useful for extracting unique transformed values from a collection.
set comprehension unique values deduplicate build set
syntax Copy
s.add(elem)
s.discard(elem)
s.remove(elem)example Copy
active = {"alice" , "bob" }
active.add("carol" )
active.discard("bob" )
active.discard("nonexistent" )
print (active)output
{'alice', 'carol'}Note discard() silently ignores missing elements. remove() raises KeyError if the element is not found. Prefer discard() when absence is acceptable.
add to set remove from set discard set add