0

trying to do simple loop and insert 0 if condition is true, but it not working.

could you please help me to solve this simple issue

Thank you

a_list = [1,2,3]
num = 0
for i in a_list:
    if len(str(i)) < 2 :
    a_list.insert(i,num)

print(a_list)

a_list must be [01,02,03] 
1
  • it still doesn't work Commented Oct 8, 2017 at 8:42

2 Answers 2

2

You are missing indentation, it should be like this :

a_list = [1,2,3]
num = 0
for i in a_list:
    if len(str(i)) < 2:
        a_list.insert(i,num)

print(a_list)

and you are doing wrong in your logic, you should replace and not insert element, you should have something like this :

a_list = [1,2,3]
num = 0
for i,e in enumerate(a_list):
    if len(str(e)) < 2:
        a_list[i]='0'+str(e);

print(a_list)
Sign up to request clarification or add additional context in comments.

Comments

1

You got it wrong. When you insert into a list, you add an item to a specific position (0 in your case). The output you want is manipulating the currect data, i.e change 1 -> 01, 2 -> 02. It's not as same as [0, 1].

a_list = [1,2,3]
num = 0
for idx, i in enumerate(a_list):
    if len(str(i)) < 2:
        a_list[idx] = '{:0>2}'.format(i)

print(a_list)  # --> ['01', '02', '03']

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.