What's the difference between the list methods append() and extend() ?
What's the difference between the list methods append() and extend() ?
In Python, the list methods append() and extend() are used to add elements to a list, but they do so in different ways.
append()The append() method adds its argument as a single element to the end of a list, regardless of its type. This means that if the argument is a list, it will be added as a single nested list. For example:
my_list = [1, 2, 3]
my_list.append([4, 5])
print(my_list) # Output: [1, 2, 3, [4, 5]]
Here, [3][4] is added as a single element to my_list.
extend()The extend() method, on the other hand, takes an iterable (such as a list, tuple, set, or string) and appends each of its elements to the list, expanding the list. Each element of the iterable is added to the list individually:
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.