In Python, What Distinguishes The List Methods Append And Extend?

In Python, the append() and extend() methods are used to add elements to a list, but they have some differences in functionality.

  1. append() method: This method is used to add an element at the end of a list. It takes a single argument and adds it as a single item to the existing list. If the argument is an iterable (like a list or tuple), it is added as a single item within the list.

Example:

my_list = [1, 2, 3]
my_list.append(4)         # [1, 2, 3, 4]
my_list.append([5, 6])    # [1, 2, 3, 4, [5, 6]]
  1. extend() method: This method is used to add elements from an iterable (like a list, tuple, or string) to the end of a list. It takes an iterable as an argument and adds each element of the iterable to the existing list, one by one.

Example:

my_list = [1, 2, 3]
my_list.extend([4, 5])         # [1, 2, 3, 4, 5]
my_list.extend((6, 7))         # [1, 2, 3, 4, 5, 6, 7]
my_list.extend("hello")        # [1, 2, 3, 4, 5, 6, 7, 'h', 'e', 'l', 'l', 'o']

In summary, append() adds a single item or an iterable as a whole to the end of a list, while extend() adds each element of an iterable to the end of a list individually.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!