파이썬에서“.append ()”와“+ = []”의 차이점은 무엇입니까?
차이점은 무엇입니까?
some_list1 = []
some_list1.append("something")
과
some_list2 = []
some_list2 += ["something"]
귀하의 경우 유일한 차이점은 성능입니다. 추가는 두 배 빠릅니다.
Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> timeit.Timer('s.append("something")', 's = []').timeit()
0.20177424499999999
>>> timeit.Timer('s += ["something"]', 's = []').timeit()
0.41192320500000079
Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> timeit.Timer('s.append("something")', 's = []').timeit()
0.23079359499999999
>>> timeit.Timer('s += ["something"]', 's = []').timeit()
0.44208112500000141
일반적으로 append
목록에 한 항목을 추가 하고 오른쪽 목록의 모든 요소를 왼쪽 목록에 +=
복사 합니다.
업데이트 : 성능 분석
바이트 코드를 비교하면 append
버전이주기를 LOAD_ATTR
+ CALL_FUNCTION
, 및 + = version-in으로 낭비 한다고 가정 할 수 있습니다 BUILD_LIST
. 분명히 + BUILD_LIST
보다 큽니다 .LOAD_ATTR
CALL_FUNCTION
>>> import dis
>>> dis.dis(compile("s = []; s.append('spam')", '', 'exec'))
1 0 BUILD_LIST 0
3 STORE_NAME 0 (s)
6 LOAD_NAME 0 (s)
9 LOAD_ATTR 1 (append)
12 LOAD_CONST 0 ('spam')
15 CALL_FUNCTION 1
18 POP_TOP
19 LOAD_CONST 1 (None)
22 RETURN_VALUE
>>> dis.dis(compile("s = []; s += ['spam']", '', 'exec'))
1 0 BUILD_LIST 0
3 STORE_NAME 0 (s)
6 LOAD_NAME 0 (s)
9 LOAD_CONST 0 ('spam')
12 BUILD_LIST 1
15 INPLACE_ADD
16 STORE_NAME 0 (s)
19 LOAD_CONST 1 (None)
22 RETURN_VALUE
LOAD_ATTR
오버 헤드 를 제거하여 성능을 더욱 향상시킬 수 있습니다 .
>>> timeit.Timer('a("something")', 's = []; a = s.append').timeit()
0.15924410999923566
당신이 준 예에서, 출력면 사이에는 차이가 없다 append
하고 +=
. 그러나 append
와 +
(질문이 원래 묻는) 차이점이 있습니다.
>>> a = []
>>> id(a)
11814312
>>> a.append("hello")
>>> id(a)
11814312
>>> b = []
>>> id(b)
11828720
>>> c = b + ["hello"]
>>> id(c)
11833752
>>> b += ["hello"]
>>> id(b)
11828720
로서 당신은 참조 할 수 append
와 +=
같은 결과를 가지고, 새 목록을 생성하지 않고 목록에 항목을 추가합니다. 를 사용 +
하면 두 목록이 추가되고 새 목록이 생성됩니다.
>>> a=[]
>>> a.append([1,2])
>>> a
[[1, 2]]
>>> a=[]
>>> a+=[1,2]
>>> a
[1, 2]
append는 목록에 단일 요소를 추가합니다.이 요소는 무엇이든 가능합니다. +=[]
목록에 가입합니다.
+ =는 과제입니다. 사용하면 실제로 'some_list2 = some_list2 + ['something ']'입니다. 할당에는 리 바인딩이 포함되므로 다음과 같습니다.
l= []
def a1(x):
l.append(x) # works
def a2(x):
l= l+[x] # assign to l, makes l local
# so attempt to read l for addition gives UnboundLocalError
def a3(x):
l+= [x] # fails for the same reason
+ = 연산자는 일반적으로 list + list와 같은 새 목록 객체를 만들어야합니다.
>>> l1= []
>>> l2= l1
>>> l1.append('x')
>>> l1 is l2
True
>>> l1= l1+['x']
>>> l1 is l2
False
그러나 실제로 :
>>> l2= l1
>>> l1+= ['x']
>>> l1 is l2
True
This is because Python lists implement __iadd__() to make a += augmented assignment short-circuit and call list.extend() instead. (It's a bit of a strange wart this: it usually does what you meant, but for confusing reasons.)
In general, if you're appending/extended an existing list, and you want to keep the reference to the same list (instead of making a new one), it's best to be explicit and stick with the append()/extend() methods.
some_list2 += ["something"]
is actually
some_list2.extend(["something"])
for one value, there is no difference. Documentation states, that:
s.append(x)
same ass[len(s):len(s)] = [x]
s.extend(x)
same ass[len(s):len(s)] = x
Thus obviously s.append(x)
is same as s.extend([x])
The difference is that concatenate will flatten the resulting list, whereas append will keep the levels intact:
So for example with:
myList = [ ]
listA = [1,2,3]
listB = ["a","b","c"]
Using append, you end up with a list of lists:
>> myList.append(listA)
>> myList.append(listB)
>> myList
[[1,2,3],['a',b','c']]
Using concatenate instead, you end up with a flat list:
>> myList += listA + listB
>> myList
[1,2,3,"a","b","c"]
The performance tests here are not correct:
- You shouldn't run the profile only once.
- If comparing append vs. += [] number of times you should declare append as a local function.
- time results are different on different python versions: 64 and 32 bit
e.g.
timeit.Timer('for i in xrange(100): app(i)', 's = [] ; app = s.append').timeit()
good tests can be found here: http://markandclick.com/1/post/2012/01/python-list-append-vs.html
In addition to the aspects described in the other answers, append and +[] have very different behaviors when you're trying to build a list of lists.
>>> list1=[[1,2],[3,4]]
>>> list2=[5,6]
>>> list3=list1+list2
>>> list3
[[1, 2], [3, 4], 5, 6]
>>> list1.append(list2)
>>> list1
[[1, 2], [3, 4], [5, 6]]
list1+['5','6'] adds '5' and '6' to the list1 as individual elements. list1.append(['5','6']) adds the list ['5','6'] to the list1 as a single element.
The rebinding behaviour mentioned in other answers does matter in certain circumstances:
>>> a = ([],[])
>>> a[0].append(1)
>>> a
([1], [])
>>> a[1] += [1]
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
That's because augmented assignment always rebinds, even if the object was mutated in-place. The rebinding here happens to be a[1] = *mutated list*
, which doesn't work for tuples.
let's take an example first
list1=[1,2,3,4]
list2=list1 (that means they points to same object)
if we do
list1=list1+[5] it will create a new object of list
print(list1) output [1,2,3,4,5]
print(list2) output [1,2,3,4]
but if we append then
list1.append(5) no new object of list created
print(list1) output [1,2,3,4,5]
print(list2) output [1,2,3,4,5]
extend(list) also do the same work as append it just append a list instead of a
single variable
The append() method adds a single item to the existing list. It doesn't return a new list, rather it modifies the original list.
some_list1 = []
some_list1.append("something")
So here the some_list1 will get modified.
Whereas using + to combine the elements of lists returns a new list.
some_list2 = []
some_list2 += ["something"]
So here the some_list2 and ["something"] are the two lists which is combined and a new list is returned which is assigned to some_list2
참고URL : https://stackoverflow.com/questions/725782/in-python-what-is-the-difference-between-append-and
'IT story' 카테고리의 다른 글
bash에서 $ @에서 첫 번째 요소 제거 (0) | 2020.07.18 |
---|---|
문자열의 주어진 색인에서 문자를 바꾸시겠습니까? (0) | 2020.07.18 |
null이 아닌 자바 스크립트 검사 (0) | 2020.07.18 |
Intellij 아이디어는 Maven에서 아무것도 해결할 수 없습니다. (0) | 2020.07.18 |
'catch'속성이 'Observable'유형에 없습니다. (0) | 2020.07.18 |