Say I wanted to create an array (NOT list) of 1,000,000 twos in python, like this:
array = [2, 2, 2, ...... , 2]
What would be a fast but simple way of doing it?
解决方案
Is this what you're after?
# slower.
twosArr = array.array('i', [2] * 1000000)
# faster.
twosArr = array.array('i', [2]) * 1000000
You can get just a list with this:
twosList = [2] * 1000000
-- EDITED --
I updated this to reflect information in another answer. It would appear that you can increase the speed by a ratio of ~ 9 : 1 by adjusting the syntax slightly. Full credit belongs to @john-machin. I wasn't aware you could multiple the array object the same way you could do to a list.