0% found this document useful (0 votes)
2 views26 pages

Built-In Functions in Python Collection

The document provides a comprehensive overview of built-in functions for Python collections, including lists, tuples, strings, sets, and more. It explains how functions like len(), sum(), any(), and all() work with different data types and discusses truthy and falsy values in Python. Additionally, it highlights practical examples and common pitfalls related to list operations, such as slicing, list comprehensions, and mutable vs immutable behavior.

Uploaded by

abinitio108
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views26 pages

Built-In Functions in Python Collection

The document provides a comprehensive overview of built-in functions for Python collections, including lists, tuples, strings, sets, and more. It explains how functions like len(), sum(), any(), and all() work with different data types and discusses truthy and falsy values in Python. Additionally, it highlights practical examples and common pitfalls related to list operations, such as slicing, list comprehensions, and mutable vs immutable behavior.

Uploaded by

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

Built-in Functions for Python Collections

Quick Reference Table

Lis Tupl Strin Rang Se Frozens


Function
t e g e t et

len() ✅ ✅ ✅ ✅ ✅ ✅

sum() ✅ ✅ ❌ ✅ ✅ ✅

max() ✅ ✅ ✅ ✅ ✅ ✅

min() ✅ ✅ ✅ ✅ ✅ ✅

sorted() ✅ ✅ ✅ ❌ ✅ ✅

any() ✅ ✅ ✅ ✅ ✅ ✅

all() ✅ ✅ ✅ ✅ ✅ ✅

enumerat
✅ ✅ ✅ ✅ ✅ ✅
e()

zip() ✅ ✅ ✅ ✅ ✅ ✅

Validation of non-iterables like None, int, float….

n1=2 #n1=None #n1=2.3

Print(bool(n1));

Validation of iterables like (ordered(sequence) Or unordered(non seq))ANY()


Str, list, tuple, rang

Set , forzenset

============

What is Considered True(Truthy)

1. Numbers: Any non-zero num


2. String: Any non empty string {s1=’’ Non-True}
3. List: Any Non empty str {l1=[] , l1=list() Non-true}
4. tuple: Any Non empty str {t1=() Non-true}
5. Set: : Any Non empty str {s1=set() Non-true}
6. Frozenset: Any Non empty str {FS1=frozenset() Non-true}
7. Range: : Any Non empty str {r1=range(0) Non-true}
8. Dict: : Any Non empty str {d1={}, d1=dict() Non-true}

COMMON FALSY VALUES in python:

False, None, 0, 0.0, “” (empty str), ‘’ , [], () , {} , set(), frozenset() . range(0)

FUNCTIONS for check truthiness:

Bool() for non itterables and in iterables it check only emptiness not all values only single
value , len()==0, any() for itterables.

data=[0,'',None]

print(bool(data)) #True bool function fails here .

print(any(data)) #false bcz it ll check all element one by one till atleast one valid element
found

==================================================

When applied to strings, they treat the string as a sequence of characters


(since strings are iterable in Python).
How any() works with strings:

any() returns True if at least one character is truthy.


python

# All characters in a non-empty string are truthy (except empty string)


print(any("hello")) # True - all characters are truthy
print(any(" ")) # True - even a space is truthy
print(any("")) # False - empty string is falsy
print(any("0")) # True - '0' is a character, not number 0
print(any("False")) # True - all characters are truthy

How all() works with strings:

all() returns True only if ALL characters are truthy.


python

print(all("hello")) # True - all characters are truthy


print(all(" ")) # True - space is truthy
print(all("")) # True - empty string is truthy (vacuously true)
print(all("Hello")) # True - all characters are truthy

===================

=================

Interesting examples:
python

# Checking if string has any digits


text = "abc123"
print(any([Link]() for c in text)) # True - has digits
# Checking if all characters are alphabetic
text = "Hello"
print(all([Link]() for c in text)) # True

text = "Hello123"
print(all([Link]() for c in text)) # False - contains digits

# Check if string contains any uppercase


text = "helloWorld"
print(any([Link]() for c in text)) # True - 'W' is uppercase

# Check if string is all uppercase


text = "HELLO"
print(all([Link]() for c in text)) # True

Common gotcha:
python

# This might not do what you expect!


word = "False"
print(any(word)) # True - because it's checking characters, not the word
"False"
print(all(word)) # True - all characters are truthy

# To check the actual boolean value of the string content:


print(any([word])) # True - [word] is a list with one element, and that
element is truthy
print(all([word])) # True - same reason

# If you want to evaluate the string as a Python expression:


word = "False"
print(any(eval(word))) # False - eval('False') gives boolean False
# Be careful with eval() though - it's dangerous with untrusted input!

Practical example: Password validation


python

password = "Pass123"
has_upper = any([Link]() for c in password)
has_lower = any([Link]() for c in password)
has_digit = any([Link]() for c in password)
has_special = any(not [Link]() for c in password)

print(f"Has uppercase: {has_upper}") # True


print(f"Has lowercase: {has_lower}") # True
print(f"Has digit: {has_digit}") # True
print(f"Has special: {has_special}") # False

is_strong = all([has_upper, has_lower, has_digit, len(password) >= 8])


print(f"Strong password: {is_strong}") # False (too short)

So yes, any() and all() work perfectly with strings, but remember they
iterate through characters, not words or lines!

=====================================

the key differences between [word], list(word), and list comprehension:

1. [word] - Creates a list with ONE element


python

word = "hello"
result = [word]
print(result) # ['hello'] - a list containing the string itself

word = 42
result = [word]
print(result) # [42] - a list containing the number

word = [1,2,3]
result = [word]
print(result) # [[1,2,3]] - a list containing the list (nested)

2. list(word) - Converts the iterable into a list


python

# With string - splits into characters


word = "hello"
result = list(word)
print(result) # ['h', 'e', 'l', 'l', 'o'] - each character as an element

# With tuple
word = (1,2,3)
result = list(word)
print(result) # [1, 2, 3]

# With range
word = range(3)
result = list(word)
print(result) # [0, 1, 2]

# With dictionary (gives keys)


word = {'a':1, 'b':2}
result = list(word)
print(result) # ['a', 'b']

# With number - ERROR!


# word = 42
# result = list(word) # TypeError: 'int' object is not iterable

3. List Comprehension - Transforms each


element
python

word = "hello"
# Basic comprehension - same as list(word)
result = [char for char in word]
print(result) # ['h', 'e', 'l', 'l', 'o']

# With transformation
result = [[Link]() for char in word]
print(result) # ['H', 'E', 'L', 'L', 'O']

# With condition
result = [char for char in word if char != 'l']
print(result) # ['h', 'e', 'o']

# With numbers
numbers = [1,2,3,4]
result = [n*2 for n in numbers if n%2==0]
print(result) # [4, 8] - double only even numbers

Visual Comparison Table

Input [1,2, Input 4


Operation Input "hello"
3] 2

[word] ['hello'] [[1,2,3]] [42]

['h','e','l','l','o
list(word) [1,2,3] ❌ Error
']

List Comp [x for x in ['h','e','l','l','o


[1,2,3] ❌ Error
word] ']

Practical Examples
python
# When you want to treat a string as a single item
keywords = ["python", "java", "javascript"]
search_terms = [keywords] # [["python", "java", "javascript"]] - list of
lists

# When you want to split a string into characters


word = "hello"
characters = list(word) # ['h', 'e', 'l', 'l', 'o']

# When you want to transform while splitting


word = "hello"
uppercase_chars = [[Link]() for c in word] # ['H', 'E', 'L', 'L', 'O']

# Real-world example: Processing user input


user_input = "hello world"

# Option 1: Treat as one item


input_list = [user_input] # ["hello world"]

# Option 2: Split into words


words = user_input.split() # ["hello", "world"]

# Option 3: Split into characters


chars = list(user_input) # ['h','e','l','l','o',' ','w','o','r','l','d']

# Option 4: Transform characters


clean_chars = [c for c in user_input if c != ' '] #
['h','e','l','l','o','w','o','r','l','d']

Summary
 [word]: Puts the entire object in a list (1 element)
 list(word): Iterates through the object and creates
list of its
elements
 List comprehension: Iterates with optional transformation/filtering

===============================

Here are some amazing and lesser-known facts about Python lists:

1. Lists can be multiplied like numbers!


python

# Repeating list elements


print([1,2,3] * 3) # [1, 2, 3, 1, 2, 3, 1, 2, 3]
print(["Hi"] * 5) # ['Hi', 'Hi', 'Hi', 'Hi', 'Hi']

# This creates new objects, careful with nested lists!


nested = [[]] * 3
nested[0].append(1)
print(nested) # [[1], [1], [1]] - all same list reference!

2. List slicing creates SHALLOW copies


python
original = [1, [2, 3], 4]
copy = original[:] # Shallow copy

copy[0] = 99 # Won't affect original (immutable)


copy[1][0] = 999 # WILL affect original (mutable nested list)

print(original) # [1, [999, 3], 4] - inner list changed!


print(copy) # [99, [999, 3], 4]

3. Negative indexing and slicing magic


python

nums = [10, 20, 30, 40, 50]

print(nums[-1]) # 50 (last element)


print(nums[-3:]) # [30, 40, 50] (last 3)
print(nums[:-2]) # [10, 20, 30] (all except last 2)
print(nums[::-1]) # [50, 40, 30, 20, 10] (reverse)
print(nums[::2]) # [10, 30, 50] (every 2nd element)
print(nums[-2:2]) # [] (backwards slice returns empty)

4. Lists can be compared lexicographically


python

print([1,2,3] < [1,2,4]) # True (compares element by element)


print([1,2,3] < [1,2,3,0]) # True (shorter list is considered smaller)
print([1,2,3] == [1.0,2,3]) # True (values compared, not types)
print([1,2,3] > [1,2]) # True

5. The * operator for unpacking is amazing


python

first, *rest = [1, 2, 3, 4, 5]


print(first) # 1
print(rest) # [2, 3, 4, 5]

*beginning, last = [1, 2, 3, 4, 5]


print(beginning) # [1, 2, 3, 4]
print(last) # 5
first, *middle, last = [1, 2, 3, 4, 5]
print(middle) # [2, 3, 4]

# Merge lists
a = [1,2,3]
b = [4,5,6]
merged = [*a, *b] # [1, 2, 3, 4, 5, 6]

6. del can slice too!


python

nums = [1, 2, 3, 4, 5, 6]
del nums[1:4] # Remove elements at index 1,2,3
print(nums) # [1, 5, 6]

nums = [1, 2, 3, 4, 5, 6]
del nums[::2] # Remove every 2nd element
print(nums) # [2, 4, 6]

7. Lists can be used as stacks AND queues


python

# As stack (LIFO) - FAST


stack = [1,2,3]
[Link](4) # Push - O(1)
item = [Link]() # Pop - O(1)

# As queue (FIFO) - SLOW for large lists


queue = [1,2,3]
[Link](4) # Enqueue - O(1)
item = [Link](0) # Dequeue - O(n) - SLOW!
# For queues, use [Link] instead

8. sort() vs sorted() - in-place vs new list


python

nums = [3,1,4,1,5]
sorted_nums = sorted(nums) # Creates new list
print(sorted_nums) # [1,1,3,4,5]
print(nums) # [3,1,4,1,5] - unchanged
[Link]() # Sorts in-place, returns None
print(nums) # [1,1,3,4,5] - changed

9. List multiplication quirk with mutable objects


python

# This creates references to the SAME inner list


matrix = [[0] * 3] * 3
matrix[0][0] = 1
print(matrix) # [[1,0,0], [1,0,0], [1,0,0]] - all rows changed!

# Correct way:
matrix = [[0] * 3 for _ in range(3)]
matrix[0][0] = 1
print(matrix) # [[1,0,0], [0,0,0], [0,0,0]]

10. List comprehensions can be nested and


conditional
python

# Nested loops in list comprehension


pairs = [(x,y) for x in [1,2,3] for y in [4,5,6]]
# [(1,4),(1,5),(1,6),(2,4),(2,5),(2,6),(3,4),(3,5),(3,6)]

# Matrix flattening
matrix = [[1,2,3],[4,5,6],[7,8,9]]
flat = [num for row in matrix for num in row]
# [1,2,3,4,5,6,7,8,9]

# Complex conditions
numbers = [1,2,3,4,5,6,7,8,9]
result = ['even' if x%2==0 else 'odd' for x in numbers]
# ['odd','even','odd','even','odd','even','odd','even','odd']

11. count() can count multiple things


python

items = [1, [1,2], 1, [1,2], 1]


print([Link](1)) # 3
print([Link]([1,2])) # 2

12. index() can search with ranges


python

nums = [1,2,3,2,4,2,5]
print([Link](2)) # 1 (first occurrence)
print([Link](2, 2)) # 3 (search starting from index 2)
print([Link](2, 4)) # 5 (search starting from index 4)
# print([Link](2, 2, 4)) # Error! 2 not found between index 2 and 4

13. Lists can be used as default arguments


(dangerous!)
python

def bad_append(item, lst=[]): # DON'T DO THIS!


[Link](item)
return lst

print(bad_append(1)) # [1]
print(bad_append(2)) # [1,2] - uses SAME list!

def good_append(item, lst=None):


if lst is None:
lst = []
[Link](item)
return lst

14. + vs += with lists


python

# + creates a new list


a = [1,2,3]
b = [4,5,6]
c = a + b # New list

# += extends in-place (more efficient)


a += b # a is modified in-place
# But careful with immutable elements in tuple!
t = ([1,2], 3)
# t += [4,5] # TypeError - can't modify tuple
t[0] += [4,5] # This works but raises an error? Try it!

15. Memory view and id() surprises


python

a = [1,2,3]
b = a # Reference copy
print(id(a) == id(b)) # True - same object

c = a[:] # Shallow copy


print(id(a) == id(c)) # False - different objects

a[0] = 99
print(b[0]) # 99 (b refers to same list)
print(c[0]) # 1 (c is a copy)

=================================================

the difference between ==, is, and truthiness checks in Python:

1. == (Equality Operator)
Compares values - checks if the contents are the same
python
a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(a == b) # True - they have the same values


print(a == c) # True - they have the same values

# Different types can be equal


print(1 == 1.0) # True - different types, same value
print(True == 1) # True - bool True equals 1
print(False == 0) # True - bool False equals 0
print([1,2] == (1,2)) # False - different types, different structure
2. is (Identity Operator)
Compares identity - checks if they are the SAME OBJECT in memory
python
a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(a is b) # False - different objects in memory


print(a is c) # True - same object (c references a)
print(id(a) == id(c)) # True - same memory address

# Interesting cases with small integers (Python caches -5 to 256)


x = 256
y = 256
print(x is y) # True - small integers are cached

x = 257
y = 257
print(x is y) # False - large integers are not cached

# Strings can be interned


s1 = "hello"
s2 = "hello"
print(s1 is s2) # True - Python interns some strings

s1 = "hello world!"
s2 = "hello world!"
print(s1 is s2) # False - longer strings may not be interned

3. Truthiness Check
Checks if a value is considered True or False in a boolean context
python
# Values considered False (falsy):
print(bool(False)) # False
print(bool(None)) # False
print(bool(0)) # False
print(bool(0.0)) # False
print(bool("")) # False (empty string)
print(bool([])) # False (empty list)
print(bool({})) # False (empty dict)
print(bool(set())) # False (empty set)
print(bool(())) # False (empty tuple)

# Values considered True (truthy):


print(bool(True)) # True
print(bool(1)) # True (any non-zero number)
print(bool(-1)) # True (any non-zero number)
print(bool(0.1)) # True (any non-zero float)
print(bool("hello")) # True (non-empty string)
print(bool([0])) # True (non-empty list, even with falsy element)
print(bool([False])) # True (list has an element, regardless of value)
print(bool("False")) # True (non-empty string)

Practical Examples Comparing All Three


python
def check_value(x):
print(f"Value: {x}")
print(f"Truthiness: {bool(x)}")
if x:
print(" → Truthy")
else:
print(" → Falsy")

# Example 1: Empty vs Non-empty


check_value([]) # Falsy
check_value([1,2]) # Truthy

# Example 2: Zero vs Non-zero


check_value(0) # Falsy
check_value(0.0) # Falsy
check_value(0.0001) # Truthy

# Example 3: Common confusion


items = []
items2 = []

print(items == items2) # True - both empty


print(items is items2) # False - different empty lists

if items: # Truthiness check


print("Has items")
else:
print("Empty") # This prints

Common Pitfalls and Best Practices


python
# DON'T DO THIS (comparing with True/False using is)
x = 1
if x is True: # Wrong! x is 1, not True
print("This won't print")

# DON'T DO THIS (truthiness confusion)


name = ""
if name is not None: # Wrong! This checks identity, not emptiness
print(f"Hello {name}") # This will still print with empty string!

# DON'T DO THIS (unnecessary boolean conversion)


if bool(x) == True: # Redundant! Just use 'if x:'

# DO THIS (proper truthiness check)


name = input("Enter name: ")
if name: # Checks truthiness (non-empty string)
print(f"Hello {name}")
else:
print("No name entered")

# DO THIS (checking for None explicitly)


value = get_something()
if value is None: # Check for None with 'is'
print("No value returned")
elif value: # Then check truthiness
print(f"Got value: {value}")

Truthiness Table for Common Types

Type Falsy Truthy

bool False True


Type Falsy Truthy

int 0 any non-zero (1, -1, 42)

float 0.0 any non-zero (0.1, -3.14)

str "" (empty) any non-empty (" ", "False")

list [] any with elements ([0], [False])

dict {} any with keys ({0:0})

tuple () any with elements ((0,))

set set() any with elements ({0})

None None N/A

custom if __bool__ returns False if __bool__ returns True

Summary
 ==:"Do these have the same value?" (content comparison)
 is:"Are these the exact same object?" (identity comparison)
 Truthiness: "Would this evaluate to True in an if statement?"
(boolean context)

==============================================

1. LIST Built-in Functions


python
numbers = [3, 1, 4, 1, 5, 9]

# 📏 len() - Count items


print(len(numbers)) # 6
# ➕ sum() - Add all numbers
print(sum(numbers)) # 23 (3+1+4+1+5+9)

# 📈 max()/min() - Find largest/smallest


print(max(numbers)) # 9
print(min(numbers)) # 1

# 🔢 sorted() - Get sorted copy


print(sorted(numbers)) # [1, 1, 3, 4, 5, 9]
print(sorted(numbers, reverse=True)) # [9, 5, 4, 3, 1, 1]

# ✅ any()/all() - Check conditions


print(any(x > 5 for x in numbers)) # True (9 > 5)
print(all(x > 0 for x in numbers)) # True (all positive)

# 🎯 enumerate() - Get index with value


for i, num in enumerate(numbers):
print(f"Index {i}: {num}")
# Output: Index 0: 3, Index 1: 1, ...

# 🤝 zip() - Combine with other lists


names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")

# 📊 reversed() - Get reversed iterator


print(list(reversed(numbers))) # [9, 5, 1, 4, 1, 3]

# 🔍 filter() - Filter elements


even = list(filter(lambda x: x % 2 == 0, numbers))
print(even) # [4]

# 🎨 map() - Apply function to all


squared = list(map(lambda x: x ** 2, numbers))
print(squared) # [9, 1, 16, 1, 25, 81]

2. TUPLE Built-in Functions (Immutable List)


python
coordinates = (10, 20, 30)
mixed = ("apple", 3, 4.5, True)

# 📏 len()
print(len(coordinates)) # 3

# ➕ sum() - For numeric tuples only


print(sum(coordinates)) # 60

# 📈 max()/min()
print(max(coordinates)) # 30
print(min(coordinates)) # 10

# 🔢 sorted()
print(sorted(coordinates)) # [10, 20, 30] (returns list!)

# ✅ any()/all()
print(any(x == 20 for x in coordinates)) # True
print(all(isinstance(x, int) for x in coordinates)) # True

# 🎯 enumerate()
for idx, val in enumerate(mixed):
print(f"{idx}: {type(val).__name__}")

# 🤝 zip() with tuple


points = [(1,2), (3,4), (5,6)]
x_coords, y_coords = zip(*points)
print(x_coords) # (1, 3, 5)
print(y_coords) # (2, 4, 6)

3. STRING Built-in Functions


python
text = "Python 3.9"
name = "Alice"

# 📏 len()
print(len(text)) # 10
# ❌ sum() - NOT APPLICABLE (can't sum characters)

# 📈 max()/min() - Based on ASCII/Unicode


print(max(text)) # 'y' (highest ASCII)
print(min(text)) # ' ' (space - lowest ASCII)

# 🔢 sorted() - Returns list of characters


print(sorted("python")) # ['h', 'n', 'o', 'p', 't', 'y']
print(sorted("Python")) # ['P', 'h', 'n', 'o', 't', 'y']

# ✅ any()/all() - Check character conditions


print(any([Link]() for c in text)) # True (has '3')
print(all([Link]() for c in name)) # True (all letters)

# 🎯 enumerate()
for i, char in enumerate("Hi!"):
print(f"Position {i}: '{char}'")

# 🤝 zip() strings
first = "abc"
second = "123"
for char, num in zip(first, second):
print(char + num) # a1, b2, c3

# 🔄 reversed()
print(''.join(reversed("hello"))) # "olleh"

# 🔍 filter() - Remove certain characters


only_alpha = ''.join(filter([Link], "Py123th!on"))
print(only_alpha) # "Python"

# 🎨 map() - Transform characters


upper_all = ''.join(map([Link], "hello"))
print(upper_all) # "HELLO"

# 📖 ord()/chr() - Character codes


print(ord('A')) # 65 (ASCII value)
print(chr(65)) # 'A'
4. RANGE Built-in Functions
python
r = range(5, 15, 2) # 5, 7, 9, 11, 13

# 📏 len()
print(len(r)) # 5

# ➕ sum()
print(sum(r)) # 45 (5+7+9+11+13)

# 📈 max()/min()
print(max(r)) # 13
print(min(r)) # 5

# ❌ sorted() - NOT NEEDED (already ordered)

# ✅ any()/all()
print(any(x > 10 for x in r)) # True
print(all(x % 2 == 1 for x in r)) # True (all odd)

# 🎯 enumerate()
for i, val in enumerate(r):
print(f"Step {i}: value {val}")

# 🤝 zip() ranges
r1 = range(3)
r2 = range(10, 13)
for a, b in zip(r1, r2):
print(a + b) # 10, 12, 14

# 🔢 list()/tuple() - Convert range


print(list(range(5))) # [0, 1, 2, 3, 4]
print(tuple(range(2, 6))) # (2, 3, 4, 5)

5. SET Built-in Functions


python
numbers = {3, 1, 4, 1, 5} # {1, 3, 4, 5} (duplicates removed)
empty_set = set()

# 📏 len()
print(len(numbers)) # 4 (not 5 - duplicates removed)

# ➕ sum()
print(sum(numbers)) # 13 (1+3+4+5)

# 📈 max()/min()
print(max(numbers)) # 5
print(min(numbers)) # 1

# 🔢 sorted() - Returns list


print(sorted(numbers)) # [1, 3, 4, 5]

# ✅ any()/all()
print(any(x > 3 for x in numbers)) # True
print(all(x > 0 for x in numbers)) # True

# 🎯 enumerate()
for idx, val in enumerate(numbers):
print(f"Element {idx}: {val}")

# 🤝 zip() sets (order may vary!)


set1 = {'a', 'b', 'c'}
set2 = {1, 2, 3}
for char, num in zip(sorted(set1), sorted(set2)):
print(f"{char}{num}")

# 🎨 map() on set
squared_set = set(map(lambda x: x**2, numbers))
print(squared_set) # {16, 1, 9, 25}

# 🔍 filter() on set
even_set = set(filter(lambda x: x % 2 == 0, numbers))
print(even_set) # {4}
6. FROZENSET Built-in Functions (Immutable
Set)
python
fs = frozenset([3, 1, 4, 1, 5]) # frozenset({1, 3, 4, 5})

# 📏 len()
print(len(fs)) # 4

# ➕ sum()
print(sum(fs)) # 13

# 📈 max()/min()
print(max(fs)) # 5
print(min(fs)) # 1

# 🔢 sorted()
print(sorted(fs)) # [1, 3, 4, 5]

# ✅ any()/all()
print(any(x == 4 for x in fs)) # True
print(all(isinstance(x, int) for x in fs)) # True

# 🎯 enumerate()
for i, val in enumerate(fs):
print(f"Element {i}: {val}")

# 🤝 zip() with frozenset


fs1 = frozenset(['x', 'y', 'z'])
fs2 = frozenset([10, 20, 30])
for a, b in zip(fs1, fs2):
print(f"{a}{b}")

# ❌ CANNOT use functions that modify (no append, add, remove, etc.)
# [Link](6) # ERROR! AttributeError

Comparison Table: Unique Behaviors


python
# 📍 sum() differences
numbers_list = [1, 2, 3]
numbers_tuple = (1, 2, 3)
text = "123" # string of digits
numbers_set = {1, 2, 3}

print(sum(numbers_list)) # ✅ 6
print(sum(numbers_tuple)) # ✅ 6
print(sum(numbers_set)) # ✅ 6
# print(sum(text)) # ❌ TypeError

# 🔢 sorted() return types


print(type(sorted([3,1,2]))) # <class 'list'>
print(type(sorted((3,1,2)))) # <class 'list'>
print(type(sorted({3,1,2}))) # <class 'list'>
print(type(sorted("cba"))) # <class 'list'>

# 📈 max()/min() with strings


words = ["apple", "zebra", "banana"]
print(max(words)) # 'zebra' (alphabetical)
print(min(words)) # 'apple'

# Empty collections
empty_list = []
empty_set = set()
empty_string = ""

print(sum(empty_list)) # 0
print(max(empty_list)) # ❌ ValueError
print(any(empty_list)) # False
print(all(empty_list)) # True (vacuous truth)

Practical Examples

Example 1: Student Grades Calculator


python
# List of student scores
grades = [85, 92, 78, 90, 88]

# Using built-in functions


print(f"Number of students: {len(grades)}")
print(f"Highest score: {max(grades)}")
print(f"Lowest score: {min(grades)}")
print(f"Average score: {sum(grades) / len(grades):.1f}")
print(f"Sorted grades: {sorted(grades)}")
print(f"Any failing (<60)? {any(g < 60 for g in grades)}")
print(f"All passing (>=50)? {all(g >= 50 for g in grades)}")

# With enumerate for student numbers


for i, grade in enumerate(grades, 1):
print(f"Student {i}: {grade}")

Example 2: Inventory Management


python
# Tuple of products (immutable)
products = ("Laptop", "Mouse", "Keyboard", "Monitor")

# Set of unique categories


categories = {"Electronics", "Accessories", "Electronics", "Peripheral"}
print(f"Unique categories: {sorted(categories)}")

# Dictionary with sets for fast lookups


inventory = {
"in_stock": {101, 102, 103},
"out_of_stock": {104, 105}
}

# Check stock using set functions


product_id = 102
print(f"Product {product_id} available? {product_id in
inventory['in_stock']}")
print(f"Total products: {len(inventory['in_stock']) |
len(inventory['out_of_stock'])}")

Example 3: Text Analysis


python
text = "Python programming is fun and Python is powerful"

# Convert to list of words


words = [Link]()
print(f"Total words: {len(words)}")

# Unique words using set


unique_words = set(words)
print(f"Unique words: {len(unique_words)}")

# Word frequency (using list/tuple functions)


word_counts = {}
for word in words:
word_counts[word] = word_counts.get(word, 0) + 1

# Find most common word


most_common = max(word_counts.items(), key=lambda x: x[1])
print(f"Most common word: '{most_common[0]}' ({most_common[1]} times)")

Memory Aid: "LMS ACES"


 L - len()
 M - max(), min()
 S - sum(), sorted()
 A - any(), all()
 C - Custom functions (map, filter, zip)
 E - enumerate()
 S - Special cases (reversed, etc.)

Key Differences Summary


1. sum() works on numbers only (not strings)
2. sorted() always returns a list
3. Sets automatically remove duplicates
4. Frozensets are immutable like tuples
5. Strings work character-by-character
6. range() is memory efficient (doesn't store all values)
7. empty collections: all([]) is True, any([]) is False

You might also like