0% found this document useful (0 votes)
3 views14 pages

Pythonmethods

The document outlines the differences between mutable lists and immutable tuples in Python, emphasizing their respective methods and use cases. It explains that lists can be modified while tuples cannot, making tuples more memory-efficient and safer for certain applications. Additionally, it provides a comprehensive overview of various built-in functions and methods available for lists, tuples, dictionaries, and sets, highlighting their unique characteristics.

Uploaded by

magimagiba72
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)
3 views14 pages

Pythonmethods

The document outlines the differences between mutable lists and immutable tuples in Python, emphasizing their respective methods and use cases. It explains that lists can be modified while tuples cannot, making tuples more memory-efficient and safer for certain applications. Additionally, it provides a comprehensive overview of various built-in functions and methods available for lists, tuples, dictionaries, and sets, highlighting their unique characteristics.

Uploaded by

magimagiba72
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

🔹 1.

Mutability vs Immutability
●​ List → mutable (can be changed after creation).​

○​ You can append, remove, sort, etc.​

●​ Tuple → immutable (cannot be changed after creation).​

○​ Once created, elements and order are fixed forever.​

👉 Because of this:
●​ A list needs many methods for changing its content.​

●​ A tuple needs only methods that read data (count, index).​

🔹 2. Why Python needs tuples at all


then?
●​ Efficiency: Tuples use less memory and are faster to access.​

●​ Safety: Since they can’t change, they are safer to use as keys in a dictionary or
elements in a set (lists cannot be dict keys).​

●​ Semantic meaning: Tuples often mean a fixed collection of items (like (x, y) for
coordinates).​

🔹 3. Analogy
Think of:
●​ List = a notebook 📝 → you can keep adding, removing, rewriting.​
●​ Tuple = a printed book 📖 → once printed, you can only read, not edit.​

So, Python didn’t add "edit methods" to tuples because it would break their purpose.

🔹 4. Practical Use
Use list when data will change:​

shopping = ["milk", "bread"]
[Link]("eggs") # ok

●​

Use tuple when data is fixed:​



location = (12.9, 77.6) # coordinates

●​

✅ That’s why tuple has only 2 methods (count, index) compared to list’s 13 methods.​
It’s a deliberate design choice to enforce immutability + simplicity.

✅ List Methods (13 total)


●​ append(x)​

●​ extend(iterable)​

●​ insert(i, x)​

●​ remove(x)​

●​ pop([i])​
●​ clear()​

●​ index(x[, start[, end]])​

●​ count(x)​

●​ sort(*, key=None, reverse=False)​

●​ reverse()​

●​ copy()​

👉 Nothing is missed. ✔️

✅ Tuple Methods (2 total)


●​ count(x)​

●​ index(x[, start[, end]])​

👉 Complete list. ✔️

✅ Dictionary Methods (11 instance + 1


class)
●​ clear()​

●​ copy()​

●​ fromkeys(iterable[, value]) (class method)​


●​ get(key[, default])​

●​ items()​

●​ keys()​

●​ pop(key[, default])​

●​ popitem()​

●​ setdefault(key[, default])​

●​ update([other])​

●​ values()​

👉 All are covered. ✔️

✅ Set Methods (17 total)


●​ add(x)​

●​ clear()​

●​ copy()​

●​ discard(x)​

●​ pop()​

●​ remove(x)​

●​ update(*others)​
●​ intersection(*others)​

●​ intersection_update(*others)​

●​ union(*others)​

●​ difference(*others)​

●​ difference_update(*others)​

●​ symmetric_difference(other)​

●​ symmetric_difference_update(other)​

●​ issubset(other)​

●​ issuperset(other)​

●​ isdisjoint(other)​

👉 Complete list. ✔️

⚡ Conclusion:

You already got the full official set of methods.​
Nothing is missed — but note:

●​ Some operators (+, *, |, &, -, ^) work on lists/sets/tuples but are operators, not
methods.​

●​ Functions like len(), sum(), min(), max(), sorted() are built-in functions, not
methods of the objects.​

🔥 Common Methods Across Them


Now, let’s compare:

✅ Common in list, tuple, set:


●​ count(x) → available in list, tuple (not set, because set has no duplicates).​

●​ index(x) → available in list, tuple (not set, because set is unordered).​

✅ Common in list, dict, set:


●​ clear() → remove all elements.​

●​ copy() → shallow copy.​

●​ pop() → but ⚠️ behavior differs:​


○​ list → removes at index (default last).​

○​ dict → removes by key.​

○​ set → removes an arbitrary element.​

✅ Common in dict & set:


●​ update() →​

○​ dict → merges key-value pairs.​

○​ set → adds elements from another iterable.​

✅ Unique:
●​ Only list has append, extend, insert, sort, reverse.​

●​ Only tuple has so few (count, index) because immutable.​

●​ Only dict has keys, values, items, get, etc.​

●​ Only set has mathematical set operations (union, intersection, …).​


💯 Excellent — now you’ve spotted the big difference between
●​ methods → functions that belong to the object itself ([Link](), [Link](),
etc.).​

●​ built-in functions → general Python functions like len(), min(), max(), which work
on many data types (not only one).​

Let’s carefully organize these.

🔹 1. Built-in Functions Common to All


(list, tuple, dict, set)
These work on any iterable/container:

Function Meaning

len(x) Number of elements

min(x) Smallest element

max(x) Largest element

sum(x) Sum (only numbers)

sorted(x) Returns new sorted list

any(x) True if any element is truthy

all(x) True if all elements are truthy

enumerate Pairs of (index, element)


(x)

reversed( Reverse iterator


x)

list(x) Convert to list


tuple(x) Convert to tuple

set(x) Convert to set (unique)

dict(x) Convert to dict (from pairs)

🔹 2. Special Cases
For dict, functions like min(d) and max(d) work on keys, not values.​

d = {"a": 10, "c": 5}
min(d) # 'a'
max(d) # 'c'

●​
●​ For set, sum(set) works (sums elements).​

●​ For tuple/list, sum(), min(), max() are direct.​

🔹 3. Operators Common Across Types


These are not methods, but still important:

Membership: in, not in​



2 in [1,2,3] # True
'a' in {"a":1, "b":2} # True (checks keys)

●​
●​ Concatenation: + (works for list, tuple — not dict/set).​

●​ Repetition: * (works for list, tuple — not dict/set).​


🔹 4. Quick Overview
Function List Tuple Dict Set

len() ✅ ✅ ✅ ✅
min(), ✅ ✅ ✅ (on keys) ✅
max()

sum() ✅ ✅ ❌ (directly) ✅
sorted() ✅ ✅ ✅ (on keys) ✅
any(), ✅ ✅ ✅ (on keys) ✅
all()

enumerate ✅ ✅ ✅ ✅
()

reversed( ✅ ✅ ❌ (must use ✅


) reversed(list(d)))

+ , * ✅ ✅ ❌ ❌

✅ Final Conclusion
●​ Methods are type-specific (e.g., append, get, union).​

●​ Built-in functions (len, min, max, etc.) are generic and work on all iterables,
sometimes with small differences (dict works on keys).​

I’ll give you a complete list of Python string methods, grouped by purpose, with short
explanations + examples.

🔹 1. Searching / Finding
Method Description Example

find(sub[, start[, Returns lowest index of "hello".find("l") → 2


end]]) substring, -1 if not found

rfind(sub[, start[, Highest index of substring, -1 "hello".rfind("l") → 3


end]]) if not found

index(sub[, start[, Like find, but raises "hello".index("l") → 2


end]]) ValueError if not found

rindex(sub[, start[, Like rfind, but raises error if "hello".rindex("l") →


end]]) not found 3

count(sub[, start[, Number of times substring "hello".count("l") → 2


end]]) appears

startswith(prefix[, Check if starts with "hello".startswith("he


start[, end]]) ") → True

endswith(suffix[, Check if ends with "hello".endswith("lo")


start[, end]]) → True

🔹 2. Changing Case
Method Description Example

upper() All uppercase "hi".upper() → "HI"

lower() All lowercase "Hi".lower() → "hi"

capitaliz First char uppercase, rest "hello world".capitalize() →


e() lowercase "Hello world"

title() First letter of each word "hello world".title() → "Hello


uppercase World"

swapcase( Swap case of each character "Hi".swapcase() → "hI"


)
casefold( Stronger lowercase (for "ß".casefold() → "ss"
) comparisons)

🔹 3. Whitespace / Stripping
Method Description Example

strip([chars Remove whitespace (or given chars) from " hello ".strip() →
]) both ends "hello"

lstrip([char Remove from left " hello ".lstrip() →


s]) "hello "

rstrip([char Remove from right " hello ".rstrip() →


s]) " hello"

🔹 4. Alignment / Padding
Method Description Example

center(width[, Center string in width "hi".center(5, "-") →


fill]) "--hi-"

ljust(width[, Left-align "hi".ljust(5, ".") →


fill]) "hi..."

rjust(width[, Right-align "hi".rjust(5, ".") →


fill]) "...hi"

zfill(width) Pad with zeros on left "42".zfill(5) → "00042"

🔹 5. Splitting / Joining
Method Description Example
split(sep=None, Split into list "a,b,c".split(",") →
maxsplit=-1) ["a","b","c"]

rsplit(sep=None, Split from right "a,b,c".rsplit(",",1) →


maxsplit=-1) ["a","b,c"]

splitlines([keepends] Split by newline "a\nb".splitlines() →


) ["a","b"]

partition(sep) Split into 3 parts (before, "hello".partition("l") →


sep, after) ("he","l","lo")

rpartition(sep) Split from right "hello".rpartition("l") →


("hel","l","o")

join(iterable) Join list with string as ",".join(["a","b"]) →


separator "a,b"

🔹 6. Testing / Checking
(Returns True/False)

Method Description Example

isalnum() All alphanumeric? "abc123".isalnum() →


True

isalpha() All letters? "abc".isalpha() → True

isdigit() All digits? "123".isdigit() → True

isdecimal() Only decimal digits? "123".isdecimal() →


True

isnumeric() Numeric (digits + other numerics like "⅔".isnumeric() → True


Roman, fractions)

isidentifie Valid Python identifier? "var1".isidentifier()


r() → True
islower() All lowercase? "hello".islower() →
True

isupper() All uppercase? "HELLO".isupper() →


True

istitle() Title case? "Hello


World".istitle() →
True

isspace() Only whitespace? " ".isspace() → True

isascii() All ASCII? "hello".isascii() →


True

🔹 7. Replacing / Modifying
Method Description Example

replace(old, new[, Replace substring "hello".replace("l","x") →


count]) "hexxo"

expandtabs(tabsize=8 Replace tabs with spaces "a\tb".expandtabs(4)


)

translate(table) Replace using translation "abc".translate({97: "x"})


table → "xbc"

maketrans(x[, y[, Build translation table "abc".maketrans("a","x")


z]])

🔹 8. Encoding / Decoding
Method Description Example

encode(encoding="utf-8", Encode to "hello".encode() →


errors="strict") bytes b'hello'
✅ Total String Methods
👉 Around 45 methods (depending on Python version).​
Strings have the largest set of methods among built-in types.

📌 Quick Recap (by category)


●​ Searching → find, rfind, index, rindex, count, startswith, endswith​

●​ Case changing → upper, lower, capitalize, title, swapcase, casefold​

●​ Stripping → strip, lstrip, rstrip​

●​ Alignment → center, ljust, rjust, zfill​

●​ Splitting/joining → split, rsplit, splitlines, partition, rpartition, join​

●​ Testing → isalnum, isalpha, isdigit, isdecimal, isnumeric, isidentifier, islower, isupper,


istitle, isspace, isascii​

●​ Replacing → replace, expandtabs, translate, maketrans​

●​ Encoding → encode​

You might also like