How to append elements in a Python list?
As Python lists are mutable, it means you can modify the list after you create it. There are two common ways in Python to add new data to a list:
-
append()
What is the use of append() method in list?
The append() method in a list helps to add a new element to the end of the list.
Syntex for append() method:
lst_name.append(new_element)
How to use append() method?
Example: Add a new item 100 at the end of the given list.
lst = ['theagleye', 40, 70, 'car']
lst.append(100)
print(lst)
Output
['theagleye', 40, 70, 'car', 100]
=== Code Execution Successful ===
Add a new item 'eagle' at the end of the given list.
lst = ['theagleye', 40, 70, 'car']
lst.append("eagle")
print(lst)
Output
['theagleye', 40, 70, 'car', 'eagle']
=== Code Execution Successful ===
How can you append multiple items to a Python list using append()?
The append() method can only add one item at a time to the end of the list. To add multiple items using append(), you would need to use it inside a loop, appending each item one by one.
lst1 = ['theagleye', 40, 70, 'car']
lst2 = [10, 20, 30, 40]
for i in lst2:
lst1.append(i)
print(lst1)
Output
['theagleye', 40, 70, 'car', 10, 20, 30, 40]
=== Code Execution Successful ===
The best way to add multiple elements to a list is by using the extend() method, as it is specifically designed for this purpose. It allows you to add multiple items to the list at once, rather than appending them one by one.
What is the extend() method and how to use it?
The extend() method in Python is used to add multiple elements from an iterable (like a list, tuple, or set) to the end of the list. Unlike append(), which adds a single element, extend() adds each element from the iterable individually to the list.
How to Use extend() metho:
To use the extend() method, simply call it on a list and pass another iterable (like another list, tuple, or set) as an argument.
Syntex:
list_name.extend(iterable)
Example for extend() in python list:
lst1 = ['theagleye', 40, 70, 'car']
lst2 = [10, 20, 30, 40]
lst1.extend(lst2)
print(lst1)
Output
['theagleye', 40, 70, 'car', 10, 20, 30, 40]
=== Code Execution Successful ===
What is List Concatenation (+) in Python?
You can concatenate two lists using the + operator, which creates a new list by combining two lists together.
Example for List Concatenation in python list:
lst1 = ['theagleye', 40, 70, 'car']
lst2 = [10, 20, 30, 40]
new_lst = lst1 + lst2
print(new_lst)
Output
['theagleye', 40, 70, 'car', 10, 20, 30, 40]
=== Code Execution Successful ===
How can you use += Operator (In-Place Addition) in the python list?
You can use the += operator to extend a list with another iterable, just like extend().
Example:
lst1 = ['theagleye', 40, 70, 'car']
lst1 += [10, 20, 30, 40]
print(lst1)
Output
['theagleye', 40, 70, 'car', 10, 20, 30, 40]
=== Code Execution Successful ===
Tags:
Leave a comment
You must be logged in to post a comment.