Adding Items to a Python List

You can add items to a list using methods like append(), insert(), or by concatenating lists.

Using append()

Example: Appending an Item

# Using append()
colors = ["Red", "Green", "Blue"]
print("Original List:", colors)
colors.append("Yellow")
print("After Append:", colors)

Output

Original List: ['Red', 'Green', 'Blue']

After Append: ['Red', 'Green', 'Blue', 'Yellow']

Explanation: The append() method adds an item to the end of the list.

Using insert()

Example: Inserting an Item

# Using insert()
animals = ["Cat", "Dog", "Elephant"]
print("Original List:", animals)
animals.insert(1, "Horse")
print("After Insert:", animals)

Output

Original List: ['Cat', 'Dog', 'Elephant']

After Insert: ['Cat', 'Horse', 'Dog', 'Elephant']

Explanation: The insert() method adds an item at the specified index.

Concatenating Lists

Example: Using + Operator

# Concatenating lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2
print("Combined List:", combined_list)

Output

Combined List: [1, 2, 3, 4, 5, 6]

Explanation: The + operator concatenates two lists to form a new list.