1

I've started learning python just a few days back and am stuck with a problem.

If, list=['tuesday','wednesday','friday','sunday']

I'm trying to write a function so i could pass in a specific index number and a value to insert and rather than using list.insert(0,'monday') then list.insert(2,'thursday') and so on I could directly pass the indexes eg. ind = [0,2....] and values = ['monday','thursday'....] and get a result as list = ['monday', 'tuesday','wednesday', 'thursday', 'friday', 'saturday', 'sunday']

tried

list = ['tuesday','wednesday','friday','sunday']
indexes = [0,1,2,3]
values = ['monday','thursday','saturday']
for index, value in (indexes, values):
    result = list.insert(index, value)
print (result)

and many other things but failed...help would be appreciated

2 Answers 2

2

There you have the solution:

list = ['tuesday','wednesday','friday','sunday']
indexes = [0,3,5]
values = ['monday','thursday','saturday']

result = list
for index in range(len(indexes)):
    result.insert(indexes[index], values[index])

print (result)

Please take into account return is just for functions

Sign up to request clarification or add additional context in comments.

Comments

0

Try this

days = ['tuesday','wednesday','friday','sunday']
indexes = [0,3,5]
values = ['monday','thursday','saturday']
for i in range(len(indexes)):
    days.insert(indexes[i], values[i])
return days

4 Comments

your code is similar to what I was trying and the output is ValueError Traceback (most recent call last) <ipython-input-1-8769b70b69ea> in <module> 2 indexes = [0,1,2,3] 3 values = ['monday','thursday','saturday'] ----> 4 for index, value in (indexes, values): 5 days.insert(index, value) 6 return days ValueError: too many values to unpack (expected 2)
Did you change the variable list to days as mentioned
be it days or list name really does not matter....but after you edits to the program, it would have worked if we gave print(days) instead of return.... and if your indexing was right....with your indexing the result would be ['monday', 'thursday', 'tuesday', 'wednesday', 'friday', 'saturday', 'sunday'] answer by @Eugenio is perfect ....cheers buddy
Yeah I just told like that because sometimes when i do that it got conflicted with python list one

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.