Reputation: 31
I have a list containing a number of ints and adding them to a second list at the index matching their value. The second list has already bin filled with placeholders ("X"). i.e:
firstlist = [2, 3, 5]
with the output:
secondlist = ['X', 'X', 2, 3, 'X', 5, 'X', 'X']
What is the best way to do so? Any help greatly appreciated!
Upvotes: 1
Views: 1590
Reputation:
Let's say you need to make a function YourFunc(inputlist,length)
where inputlist
argument is the list for input and length
is the argument for the length of the list for output.
So, according to your question, inputlist=[2,3,5]
and length=8
.
def YourFunc(inputlist,length):
out=[]
for X in range (0,length):
if inputlist.count(X)==1:
out.append(X)
elif inputlist.count(X)==0:
out.append('X')
print(out)
YourFunc([2,3,5],8)
So, this is how I usually do.
In this function a loop is running from 0
to length
. If the is element is not in inputlist
then 'X'
is inserted in output list out
. If not, then the number in the loop is inserted.
Upvotes: 0
Reputation: 1468
This will take a list argument and put them into a new list to be returned by the function.
def list_fill(first_list, fill, length=None):
return [(i if i in first_list else fill) for i in (range(max(first_list) + 1) if length is None else range(length))]
How list_fill
works:
The first_list
argument includes the indexes to be changed.
The fill
argument is what the empty spaces should be.
The third optional length
argument specifies the length of the output. If left blank, it will take the max index specified in first_list
.
Upvotes: 1
Reputation: 1
You could use .insert() if you want to keep the stuff that's already in secondlist.
firstlist = [2, 3, 5]
secondlist = ['X', 'X', 'X', 'X', 'X']
for x in range(len(firstlist)):
secondlist.insert(firstlist[x], firstlist[x])
print(secondlist)
Upvotes: 0
Reputation: 483
Are you looking for something as simple as this:
firstlist = [2, 3, 5]
secondlist = ['X']*10
for index in firstlist:
secondlist[index] = index
print(secondlist)
# ['X', 'X', 2, 3, 'X', 5, 'X', 'X', 'X', 'X']
Could have a dict
for firstlist
with indices for key
and the value you want to place as values
for the dict
.
Upvotes: 0