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

  • Generators in Python

    Generators in Python What is a Generator? A generator is a special type of iterator that allows you to iterate over a sequence of values without storing them all in memory at once. Generators generate values on-the-fly (lazy evaluation) using the yield keyword. Key Characteristics Basic Syntax python def generator_function(): yield value1 yield value2 yield value3 Simple Examples Example…

  • Demo And course Content

    What is Python? Python is a high-level, interpreted, and general-purpose programming language known for its simplicity and readability. It supports multiple programming paradigms, including: Python’s design philosophy emphasizes code readability (using indentation instead of braces) and developer productivity. History of Python Fun Fact: Python is named after Monty Python’s Flying Circus (a British comedy show), not the snake! 🐍🎭 Top Career Paths After Learning Core Python 🐍…

  • Python Program to Check Pangram Phrases

    Python Program to Check Pangram Phrases What is a Pangram? A pangram is a sentence or phrase that contains every letter of the alphabet at least once. Method 1: Using Set Operations python def is_pangram_set(phrase): “”” Check if a phrase is a pangram using set operations “”” # Convert to lowercase and remove non-alphabetic characters…

  • Lambda Functions in Python

    Lambda Functions in Python Lambda functions are small, anonymous functions defined using the lambda keyword. They can take any number of arguments but can only have one expression. Basic Syntax python lambda arguments: expression Simple Examples 1. Basic Lambda Function python # Regular function def add(x, y): return x + y # Equivalent lambda function add_lambda =…

  • Python Nested Lists

    Python Nested Lists: Explanation & Examples A nested list is a list that contains other lists as its elements. They are commonly used to represent matrices, tables, or hierarchical data structures. 1. Basic Nested List Creation python # A simple 2D list (matrix) matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]…

  • 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 *