0
list_from=[1,2,3,4,5,6,7,8,9,10]
list_from2=[a,b,c,d,e,f,g,h,i,j]
from_dict={list_from[i]:list_from2[i] for i in range(len(list_from2))}
list_to = [1,2,5,10]
save=[]
num=0
while num<=len(list_to):
    try:
        if list_to[num] in list_from:
            save.append(from_dict[list_to[num]])
        else:
            save.append('')
       num+=1
   except:
        break

I have the code like the above. I want to convert this while loop code to for loop. (Also, if possible, I want convert to list comprehension code) How can I do this? Thanks for your help.

4
  • I think i had a mistake the code. It seems empty list 'save' enter twice. Sorry about that. Commented Aug 28, 2020 at 13:56
  • for number in list_from Commented Aug 28, 2020 at 13:58
  • from_dict = dict(zip(list_from, list_from2)) would be simpler. Commented Aug 28, 2020 at 14:15
  • as would save = [from_dict.get(x, '') for x in list_to]. Commented Aug 28, 2020 at 14:16

2 Answers 2

4

You can just replace your

num = 0
while num <= len(list_to):

By

for num in range(0, len(list_to)):

This way, your variable "num" would automatically take value 0, then 1, ... len(list_to)-1

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

Comments

1

With For loop

for i in range(len(list_to)):
    if list_to[i] in list_from:
        save.append(from_dict[list_to[i]])
    else:
        save.append('')

Comments

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.