Note that I confirmed the difference in the behavior of the ʻappend ()and
+ =` operators when adding data to a list in Python.
Regardless of the type (character string type, numeric type, dictionary type, array type, etc.), the specified data is added to the array as one element.
>>> d_list = []
>>> d_list.append('Hello')
>>> d_list.append(123)
>>> d_list.append({'a':1, 'b':2, 'c':3})
>>> d_list.append([1, 2, 3])
>>> d_list
['Hello', 123, {'a': 1, 'b': 2, 'c': 3}, [1, 2, 3]]
+ =
It acts as an iterator and adds all the iterable elements of the specified data to the array. The operation is the same as ʻextend ()`.
Each character is added as one element in the character string type data.
>>> d_list = []
>>> d_list += 'Hello'
>>> d_list
['H', 'e', 'l', 'l', 'o']
Numeric type data is not iterable, so an error will occur.
>>> d_list += 123
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
In dictionary type data, the key name of each element is added as one element.
>>> d_list = []
>>> d_list += {'a':1, 'b':2, 'c':3}
>>> d_list
['a', 'b', 'c']
For array type data, each element is added as one element.
>>> d_list = [1, 2]
>>> d_list += [3, 4, 5]
>>> d_list
[1, 2, 3, 4, 5]
5.1. A little more about list types
list.append(x) Add an element to the end of the list. Equivalent to a [len (a):] = [x].
list.extend(iterable) Extend the list by adding all the elements of the iterable to the target list. Equivalent to a [len (a):] = iterable.
that's all
Recommended Posts