I have a list of items
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
or any other list of 16 items.
How to replace the first 12 items with '#'
?
CodePudding user response:
One possible solution:
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
lst[:12] = "#" * 12
print(lst)
Prints:
['#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', 13, 14, 15, 16]
CodePudding user response:
You can use list slicing and concatenation:
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
print(['#'] * 12 arr[12:])
Output:
['#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', 13, 14, 15, 16]
The expression
['#'] * 12 arr[12:]
simply takes ['#']
, multiplies it with 12
to make it
['#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#', '#']
and concatenates it with the element of arr
after the 12th element.