If you want to append an item to a list in multiple times, for effectively doing this:
 |
| python list append multiple times |
For Example:
METHOD #01
list = []
xval = 0
for i in range(100):
list.append(xval)
METHOD #02)
For Different data types:
list = [0] * 20
# [0, 0, 0, 0, 0, ...] It's get result all zeros up to 20 times
Similarly
list = ['pythonslearning'] * 100
# ['pythonslearning', 'pythonslearning', 'pythonslearning', 'pythonslearning', ...]
METHOD #03)
list = [{} for x in range(20)]
In the above method the second one is best
method for constant values, like as int or string. but why? the answer is when we use the syntax like
<list>*<number>only a shallow copy is does and if we use something like as syntax
[{}]*100 then it end up with 100
references to the same dictionary and hence change one of them would change them all. and the result is int and string are immutable.
You can use the extend() methods of that list If you want to add to an existing lists.
Method #01) list.extend()
Method #02) generator expression:
#l.extend(generate_value() for _ in range(n))
This will add a value n times. Note that this will evaluate generate_value() each time, side-stepping issues with mutable values that other answers may have
>>> [[5]] * 4
[[5], [5], [5], [5]
>>> _[0].append(1)
[[5, 5], [5, 5], [5, 5], [5, 5], [5, 5]]
>>> _
>>> [[5] for _ in range(5)]
[[5], [5], [5], [5], [5]]
[[5, 5], [5], [5], [5], [5]]
>>> _[0].append(1)
>>> _
When using the First method like multiplication method,we end up with a lists of n reference to the same lists.
When using second method like a generator expressions or lists comprehension,for this method a new lists is created for each sub-item, so each item is a different value in every time.