Operations on lists
Just like we could add two strings together or multiply a string by a number, we can do those operations for lists as well. We can add two lists together, which will result in a concatenation of the two. We can multiply a list by an integer
n
, which will repeat the list n
times.l1 = [1, 'abc']
l2 = [2, 'def']
print(l1 + l2) # [1, 'abc', 2, 'def']
print(l1 * 5) # [1, 'abc', 1, 'abc', 1, 'abc', 1, 'abc', 1, 'abc']
We can even modify the list in place with
+=
:l1 = [1, 'abc']
l2 = [2, 'def']
l1 += l2
print(l1) # [1, 'abc', 2, 'def']
print(l2) # [2, 'def']
To initialize a list of numbers with size
n
, we can simply multiply [0]
by n
:n = 10
l = [0] * n
print(l) # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
l[1] = 7
print(l) # [0, 7, 0, 0, 0, 0, 0, 0, 0, 0]
Challenge
Given two integers
x
and n
, your task is to define an array of n
elements filled with x
as an initial value and print it.Input | Output |
10
2 | [10, 10] |
7
3 | [7, 7, 7] |
Constraints
Time limit: 2 seconds
Memory limit: 512 MB
Output limit: 1 MB