Câu hỏi phỏng vấn Python
Câu hỏi

What's the difference between the list methods append() and extend() ?

Câu trả lời

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:

python Copy
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[1][2][3][4][5][6][7][8].

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:

python Copy
my_list = [1, 2, 3]
my_list.extend([4, 5])
print(my_list)  # Output: [1, 2, 3, 4, 5]

In this case, each element of [3][4] is added to my_list individually[1][2][3][4][5][6][7][8].

Key Differences

  • Input Type: append() takes a single element; extend() takes an iterable.
  • Effect on List: append() adds the argument as a singl...
middle

middle

Gợi ý câu hỏi phỏng vấn

middle

Is there a tool to help find bugs or perform static analysis?

senior

Can you explain Closures (as they relate to Python)?

middle

Explain the UnboundLocalError exception and how to avoid it?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào