Skip to content

Methods Reference πŸš€ΒΆ

Prerequisites: Python Data Structures

Mentor's Note: Methods are like the "Special Moves" of an object. A String has different moves than a List. Use this page whenever you forget the exact name of a move! πŸ’‘


🌟 The Scenario: The Multi-Tool πŸ› οΈΒΆ

Imagine you have a high-tech tool that changes its heads.

  • The Logic:
    • When you attach the String Head πŸ”‘, you can upper() (Scale) or strip() (Clean).
    • When you attach the List Head πŸ›οΈ, you can append() (Add) or sort() (Arrange).
  • The Result: You use the same tool (Your Code) but switch "Heads" (Methods) based on the data you are handling. βœ…

πŸ“– Essential Methods by TypeΒΆ

1. String Methods (The Cleaners) πŸ”‘ΒΆ

Remember: These return a NEW string. - .upper() / .lower(): Change case. - .strip(): Remove leading/trailing spaces. 🧹 - .replace(old, new): Swap parts of the text. - .split(sep): Break a string into a List.

2. List Methods (The Organizers) πŸ›οΈΒΆ

Remember: These change the ORIGINAL list. - .append(x): Add item to the end. - .insert(i, x): Add at a specific spot. - .pop(i): Remove and return an item. - .sort(): Put in alphabetical/numeric order.

3. Dictionary Methods (The Librarians) πŸ“–ΒΆ

  • .keys(): Get all the labels.
  • .values(): Get all the data.
  • .get(key, default): Safely look up a value without crashing. πŸ›‘οΈ

🎨 Visual Logic: Mutability Check¢

graph LR
    A[String: 'Hi'] -- .upper --> B[New Object: 'HI']
    C[List: 1, 2] -- .append 3 --> D[Same Object: 1, 2, 3]

    style B fill:#dfd
    style D fill:#ddf

πŸ’» Implementation: Method LabΒΆ

# πŸš€ Action: Chaining methods together

# πŸ›’ Scenario: Cleaning user input
raw_input = "  VISHNU_DIGITAL  "

# 🧹 Clean -> Lowercase -> Replace
clean_name = raw_input.strip().lower().replace("_", " ")

print(f"Final Name: '{clean_name}' βœ…")
# Output: 'vishnu digital'

πŸ“Š Sample Dry Run (Dictionary .get)ΒΆ

Goal: Look for 'age' in D = {"name": "VD"}

Step Instruction Logic Result
1 D["age"] Direct access CRASH πŸ’₯ (KeyError)
2 D.get("age", 0) Safe access 0 (Returns default) πŸ›‘οΈ

πŸ’‘ Interview Tip πŸ‘”ΒΆ

"Interviewers love asking: 'Why can't we sort a string in-place?' Answer: Because Strings are Immutable! You have to convert them to a list, sort, and join them back."


πŸ’‘ Pro Tip: "Good names are the best documentation. If you name your variables well, your code tells a story." - Anonymous


← Back: Built-in Reference | Next: Python MCQs β†’