What is the difference between Python's list methods append and extend?
append() method adds an item to the end of the list. The item can be of any type, and you can use the method to add multiple items by separating them with a comma. For example:
fruits = ['apple', 'banana', 'mango'] fruits.append('orange') print(fruits) # Output: ['apple', 'banana', 'mango', 'orange'] fruits.append('grapes', 'strawberry') print(fruits) # Output: ['apple', 'banana', 'mango', 'orange', 'grapes', 'strawberry']
On the other hand, the
extend() method takes an iterable (such as a list) and adds each element of the iterable to the list one by one. For example:
fruits = ['apple', 'banana', 'mango'] new_fruits = ['orange', 'grapes', 'strawberry'] fruits.extend(new_fruits) print(fruits) # Output: ['apple', 'banana', 'mango', 'orange', 'grapes', 'strawberry']
In summary, the main difference between
extend() is that
append() adds a single item to the list, while
extend() adds multiple items to the list.
Understanding slicing in Python?
Slicing is a way of extracting a specific part of an array. The syntax is following: mylist[start:end] # items start through end-1 mylist[start:] # items start through the rest of the array ...Questions
What are metaclasses in Python?
In Python, a metaclass is the class of a class. It defines how a class behaves, including how it is created and how it manages its instances. A metaclass is defined by inheriting from the built-in ...Questions
How to flatten a list in Python?
You can flatten a list in python using the following one-liner: flat_list = [item for sublist in l for item in sublist] In the example above, l is the list of lists that is to be flattened. The pre...Questions
How to copy files in Python?
To copy a file in Python, you can use the shutil module. Here is an example of how you can use the shutil.copy() function to copy a file: import shutil shutil.copy('/path/to/source/file', '/path/to...Questions
We are hiring.
Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.
Help us in making the internet more reliable.
Help us with developer education and get paid.
Reliability is the
Delightful observability tools that turn your logs & monitoring into a secret weapon for shipping better software faster.Explore Better Stack