append(), extend(), and insert() methods in Python lists

append()extend(), and insert() methods in Python lists, along with slicing where applicable.


1. append() Method

Adds a single element to the end of the list.

Examples:

  1. Adding an integer:pythonnumbers = [1, 2, 3] numbers.append(4) print(numbers) # Output: [1, 2, 3, 4]
  2. Adding a string:pythonfruits = [“apple”, “banana”] fruits.append(“cherry”) print(fruits) # Output: [“apple”, “banana”, “cherry”]
  3. Adding a list (as a single element):pythonlist1 = [1, 2] list1.append([3, 4]) print(list1) # Output: [1, 2, [3, 4]]
  4. Using slicing + append:pythonnums = [10, 20, 30] nums[len(nums):] = [40] # Same as append(40) print(nums) # Output: [10, 20, 30, 40]

2. extend() Method

Adds multiple elements (iterable items) to the end of the list.

Examples:

  1. Extending with a list:pythonnums = [1, 2] nums.extend([3, 4]) print(nums) # Output: [1, 2, 3, 4]
  2. Extending with a string (each character is added):pythonletters = [‘a’, ‘b’] letters.extend(“cd”) print(letters) # Output: [‘a’, ‘b’, ‘c’, ‘d’]
  3. Extending with a tuple:pythonitems = [1, 2] items.extend((3, 4)) print(items) # Output: [1, 2, 3, 4]
  4. Using slicing + extend:pythonlist1 = [1, 2] list1[len(list1):] = [3, 4] # Same as extend([3, 4]) print(list1) # Output: [1, 2, 3, 4]

3. insert() Method

Inserts an element at a specific position.

Examples:

  1. Inserting at index 0:pythonnums = [2, 3] nums.insert(0, 1) # Insert 1 at the beginning print(nums) # Output: [1, 2, 3]
  2. Inserting in the middle:pythonfruits = [“apple”, “cherry”] fruits.insert(1, “banana”) print(fruits) # Output: [“apple”, “banana”, “cherry”]
  3. Inserting at the end (like append):pythonnums = [1, 2] nums.insert(2, 3) # Same as append(3) print(nums) # Output: [1, 2, 3]
  4. Using slicing + insert:pythonlist1 = [10, 30] list1[1:1] = [20] # Inserts 20 at index 1 print(list1) # Output: [10, 20, 30]

Key Differences:

MethodModifies List?Adds Single/Multiple Elements?Position
append()✅ YesSingle element (even if it’s a list)End
extend()✅ YesMultiple elements (iterable)End
insert()✅ YesSingle elementSpecified index

Similar Posts

  • String Alignment and Padding in Python

    String Alignment and Padding in Python In Python, you can align and pad strings to make them visually consistent in output. The main methods used for this are: 1. str.ljust(width, fillchar) Left-aligns the string and fills remaining space with a specified character (default: space). Syntax: python string.ljust(width, fillchar=’ ‘) Example: python text = “Python” print(text.ljust(10)) #…

  • group() and groups()

    Python re group() and groups() Methods Explained The group() and groups() methods are used with match objects to extract captured groups from regex patterns. They work on the result of re.search(), re.match(), or re.finditer(). group() Method groups() Method Example 1: Basic Group Extraction python import retext = “John Doe, age 30, email: john.doe@email.com”# Pattern with multiple capture groupspattern = r'(\w+)\s+(\w+),\s+age\s+(\d+),\s+email:\s+([\w.]+@[\w.]+)’///The Pattern: r'(\w+)\s+(\w+),\s+age\s+(\d+),\s+email:\s+([\w.]+@[\w.]+)’Breakdown by Capture…

  • Class06,07 Operators, Expressions

    In Python, operators are special symbols that perform operations on variables and values. They are categorized based on their functionality: ⚙️ 1. Arithmetic Operators ➕➖✖️➗ Used for mathematical operations: Python 2. Assignment Operators ➡️ Assign values to variables (often combined with arithmetic): Python 3. Comparison Operators ⚖️ Compare values → return True or False: Python…

  • Bank Account Class with Minimum Balance

    Challenge Summary: Bank Account Class with Minimum Balance Objective: Create a BankAccount class that automatically assigns account numbers and enforces a minimum balance rule. 1. Custom Exception Class python class MinimumBalanceError(Exception): “””Custom exception for minimum balance violation””” pass 2. BankAccount Class Requirements Properties: Methods: __init__(self, name, initial_balance) deposit(self, amount) withdraw(self, amount) show_details(self) 3. Key Rules: 4. Testing…

Leave a Reply

Your email address will not be published. Required fields are marked *