Python list replication All In One
error
For the reference value list, using the
list
*number
does not work as you expected.
# reference value list
letter_lists = [['A', 'B']]
number_lists = [[1, 2]]
strs = letter_lists * 2
nums = number_lists * 2
print('strs =', strs)
print('nums =', nums)
# strs = [['A', 'B'], ['A', 'B']]
# nums = [[1, 2], [1, 2]]
strs[0][1] = "❌"
nums[0][1] = "❌"
print('strs =', strs)
print('nums =', nums)
# strs = [['A', '❌'], ['A', '❌']]
# nums = [[1, '❌'], [1, '❌']]
solution
Using the literal to create a list is OK because it does not reuse any item in the original list.
# literal list
strs = [['A', 'B'], ['A', 'B']]
nums = [[1, 2], [1, 2]]
print('strs =', strs)
print('nums =', nums)
# strs = [['A', 'B'], ['A', 'B']]
# nums = [[1, 2], [1, 2]]
strs[0][1] = "✅"
nums[0][1] = "✅"
print('strs =', strs)
print('nums =', nums)
# strs = [['A', '✅'], ['A', 'B']]
# nums = [[1, '✅'], [1, 2]]
For the primary value list, use the list
* number
is OK
# primary value list
letter_list = ['A', 'B']
number_list = [1, 2]
strs = letter_list * 2
nums = number_list * 2
print('strs =', strs)
print('nums =', nums)
# strs = ['A', 'B', 'A', 'B']
# nums = [1, 2, 1, 2]
strs[1] = "✅"
nums[1] = "✅"
print('strs =', strs)
print('nums =', nums)
# strs = ['A', '✅', 'A', 'B']
# nums = [1, '✅', 1, 2]
The reason is that you do not have a deep understanding of the list data type when using list
* number
to create a new copy of the list in Python.