Python列表的建造者模式:extend返回None的原因及相关咨询
list.extend() and "Builder-like" Patterns for Python Lists Hey, I totally get why you were confused with list.extend() returning None—been there, done that! Let’s break this down clearly.
Why extend() Returns None
Python’s design philosophy for mutable objects (like lists) makes a clear distinction between in-place modifications and operations that return new objects. Methods like extend(), append(), and sort() are all meant to tweak the original list directly, so they intentionally return None to signal that no fresh object was created.
Here’s a quick example to drive this home:
original = [1, 2, 3] result = original.extend([4, 5]) print(result) # Output: None print(original) # Output: [1, 2, 3, 4, 5] (original was modified in-place)
If you accidentally assign the result of extend() to a variable, you’ll end up with None—that’s exactly what tripped you up!
Alternatives to Get a New List
If you don’t want to mess with the original list and instead want a combined new list, you’ve got a couple solid options:
- Use the
+operator, which spits out a brand new list:original = [1, 2, 3] new_list = original + [4, 5] print(new_list) # Output: [1, 2, 3, 4, 5] print(original) # Output: [1, 2, 3] (totally unchanged) - Use
itertools.chainto stitch together multiple iterables (perfect for combining more than two lists):import itertools list1 = [1, 2] list2 = [3, 4] list3 = [5] new_list = list(itertools.chain(list1, list2, list3)) print(new_list) # Output: [1, 2, 3, 4, 5]
Is There a Built-in Builder Pattern for Lists?
Python doesn’t have a dedicated, out-of-the-box list builder class like some other languages, but it’s super easy to roll your own if you want that fluent, chainable syntax. Here’s a simple implementation:
class ListBuilder: def __init__(self): self._internal_list = [] def add(self, item): self._internal_list.append(item) return self # Return self to enable chaining def extend(self, items): self._internal_list.extend(items) return self # Same trick for chaining def build(self): return self._internal_list.copy() # Return a copy to avoid external meddling # Usage example my_list = (ListBuilder() .add(1) .add(2) .extend([3, 4]) .add(5) .build()) print(my_list) # Output: [1, 2, 3, 4, 5]
Alternatively, list comprehensions are Python’s native way to "build" lists concisely—they’re not exactly the builder pattern, but they serve a similar purpose of constructing lists declaratively:
even_numbers = [x for x in range(10) if x % 2 == 0] print(even_numbers) # Output: [0, 2, 4, 6, 8]
Wrap-Up
- Stick with
extend()if you want to modify a list in-place. - Use
+oritertools.chainif you need a new list without touching the original. - Roll your own
ListBuilderclass if you prefer chainable, builder-style syntax.
内容的提问来源于stack exchange,提问作者WestCoastProjects

