What is the difference between Python's list methods append and extend?
The 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 append()
and extend()
is that append()
adds a single item to the list, while extend()
adds multiple items to the list.
-
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 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 -
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 -
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
Make your mark
Join the writer's program
Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.
Write for usBuild on top of Better Stack
Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.
community@betterstack.comor submit a pull request and help us build better products for everyone.
See the full list of amazing projects on github