简体   繁体   中英

Python: Extending the result from the built-in list() function

I have an original list whose contents are determined in another function, and I wish to add the numbers 0 and 5 to the list to make an extended list, without corrupting the original. In this application, I know that 0 and 5 will never be part of the original list, so I am not concerned with duplication. And I am not concerned with the order or the elements either.

  1. For reasons discussed in another question, the following does not work because it corrupts the original list:

     >>> orig = [1,6] >>> extended = orig >>> extended.extend([0,5]) >>> extended [1, 6, 0, 5] >>> orig [1, 6, 0, 5] 
  2. One of the solutions proposed is to use the built-in list() function. This produces the desired result:

     >>> orig = [1,6] >>> extended = list(orig) >>> extended.extend([0,5]) >>> extended [1, 6, 0, 5] >>> orig [1, 6] 
  3. Then I attempted to combine the 2nd and 3rd lines of 2. This produces a 'None' result, and only if you print it.

     >>> orig = [1,6] >>> extended = list(orig).extend([0,5]) >>> extended >>> print extended None 
  4. What I eventually coded, which is neater than any of the previous attempts, is this, using concatenation.

     >>> orig = [1,6] >>> extended = orig + [0,5] >>> extended [1, 6, 0, 5] >>> orig [1, 6] 

But my question is, why won't example 3 work? It looks reasonable (to me), and it doesn't return an error. It just produces 'None'.

I am using Python 2.7.8.

extend is an inplace operation, like list.sort , list.append it affects the original list. All those methods because they don't return any value return None so you are simply seeing the return value of extend when you extended = list(orig).extend([0,5]) .

In [6]:  l = [1,2,3]  
In [7]: e = l.extend([4,5])    
In [8]: print e
None
In [9]:  l = [1,2,3]  
In [10]: a = l.append(6)    
In [11]: print a
None

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM