Difference Between List append and extend in Python

1. Introduction

In Python, lists are dynamic arrays that can store items of various types. Two common methods for modifying lists are append and extend. The append method adds its argument as a single element to the end of a list, while extend concatenates the first list with another list (or any iterable).

2. Key Points

1. Function: append adds an item to the end of the list, extend adds elements of an iterable to the list.

2. Argument Type: append takes a single element, and extend takes an iterable (like a list, set, or tuple).

3. Result: append increases the list length by one, extend can increase by more than one.

4. Usage: Use append for a single item, and extend for adding multiple items from another iterable.

3. Differences

Aspect Append Extend
Function Adds a single element Adds elements of an iterable
Argument Type Single element Iterable
Result Increases length by 1 Can increase the length by more than 1
Usage For a single item For adding multiple items

4. Example

# Example of Append
my_list = [1, 2, 3]
my_list.append(4)

# Example of Extend
another_list = [1, 2, 3]
another_list.extend([4, 5])

Output:

Append Output:
[1, 2, 3, 4]
Extend Output:
[1, 2, 3, 4, 5]

Explanation:

1. With append, 4 is added as a single element, increasing the list length by one.

2. With extend, the elements 4 and 5 from the new list are added, increasing the length by two.

5. When to use?

- Use append when you need to add a single item to the end of the list.

- Use extend when you have multiple items (in the form of another iterable) that you want to add to the list.

Related Python Posts:

Difference Between Local and Global Variables in Python

Difference Between List and Tuple in Python

Difference Between Array and List in Python

Difference Between List and Dictionary in Python

Difference Between List, Tuple, Set and Dictionary in Python

Difference Between a Set and Dictionary in Python

Difference between for loop and while loop in Python

Difference Between pass and continue in Python

Difference Between List append and extend in Python

Difference Between == and is operator in Python

Difference Between Deep and Shallow Copy in Python

Class Method vs Static Method in Python

Class Method vs Instance Method in Python

Difference Between List and Set in Python

Difference Between Generator and Iterator in Python

Difference Between str and repr in Python

Method Overloading vs Overriding in Python

Difference Between Dictionary and Tuple in Python

Difference Between Dictionary and Object in Python

Difference Between Mutable and Immutable in Python

Difference Between Interface and Abstract Class in Python

Difference Between Python Script and Module

Difference Between for Loop and Iterator in Python

Comments