Given a list L write a program to make a new list and match the numbers inside list L to its respective index in the new list. Put 0 at remaining indexes. Also print the elements of the new list in the single line. (See explanation for more clarity.)
Input:
[1,5,6]
Output:
0 1 0 0 0 5 6
Explanation:
List L contains 1,5,9 so at 1,5,9, index of new list the respective values are put and rest are initialized as zero.
Python Program:
L=[int(i) for i in input().split()]
new_list = [0] *(max(L)+1)
for i in range(len(new_list)):
if i in L:
new_list[i] = i
print(*new_list,end="")
Explanation :
The first line takes input from the user using the
input()
function, which is then split into a list of integers using a list comprehension. Each element in the input string is first converted to an integer using theint()
constructor, and the resulting list of integers is assigned to the variableL
.The second line creates a new list
new_list
containing(max(L) + 1)
zeros, wheremax(L)
is the largest element inL
. This creates a list with enough space to store all the elements inL
at their respective indices.The
for
loop iterates over each indexi
in the range from0
to the length ofnew_list
minus one, using therange()
function.Inside the loop, the
if
statement checks if the valuei
is present inL
. If it is, then the value at indexi
innew_list
is updated to matchi
. This means that if the valuex
appears inL
, thennew_list[x]
will be updated tox
.Finally, the
print()
function is used to print the values innew_list
in a single line, using the*
operator to unpack the list and theend
parameter to specify an empty string as the separator between values. This means that the values innew_list
will be printed without any separators between them.
Overall, this code generates a new list new_list
with the same length as L
, where the values from L
are placed at their respective indices in new_list
. The remaining indices in new_list
are filled with zeros. Finally, the values in new_list
are printed in a single line.
No comments:
Post a Comment