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

Leave a Reply

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