You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何不使用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 from y directly to the original x list.
  • This modifies x in-place, just like the native list.extend() method—no new list is created, and the original x gets all elements from y added 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:52:50