如何不使用list.extend方法与+运算符扩展列表x
Custom Extend Function Without Using
list.extend or + Let's work through this together! The problem with your x = y approach is that you're just reassigning the variable x to point to the same list as y—you aren't actually adding elements to the original x list. That's why your original x stayed unchanged when you checked the result.
Here's how to build a function that mimics list.extend by modifying x in-place, without using extend or the + operator:
def custom_extend(x, y): # Loop through each item in y and add it to x one by one for item in y: x.append(item)
How to test it:
x = [1, 2, 3] y = [4, 5, 6] custom_extend(x, y) print(x) # Output: [1, 2, 3, 4, 5, 6] print(y) # Output: [4, 5, 6] (y stays as it is)
Why this works:
- We use
list.append()(which isn't restricted by your requirements) to add each element fromydirectly to the originalxlist. - This modifies
xin-place, just like the nativelist.extend()method—no new list is created, and the originalxgets all elements fromyadded to its end.
If you wanted another approach (even avoiding append), you could use slice assignment too:
def custom_extend(x, y): x[len(x):] = y
This works because x[len(x):] targets the empty slice at the end of x, and assigning y to that slice inserts all elements of y right where we want them.
内容的提问来源于stack exchange,提问作者Python
相关产品推荐
相关产品推荐

