Search code examples
pythonlist-comprehension

how to creat list compersion with 2 IFs with 3 expersions


I was struggling with syntax to convert the below code to list comprehension but no luck,

x = ['3', '15', '161', '2', '4113', '26', '1141', '00', '05', '02', '064']
c = []
for i in x:
   if len(i) <= 2:
      i = '00' + i
   if len(i) <= 3:
      i = '0' + i
   c.append(i)

how to place the second condition:

['00' + i for i in x if len(i) <= 2 if len(i) <= 3]

Solution

  • You are never not appending a value to your new list, so you don't need filters on your list comprehension. You're just changing what you're appending.

    [f'000{d}' if len(d) == 1 else \
      f'00{d}' if len(d) == 2 else \
       f'0{d}' if len(d) == 3 else \
             d 
     for d in x]
    # ['0003', '0015', '0161', '0002', '4113', '0026', 
    #  '1141', '0000', '0005', '0002', '0064']
    

    But you can simply use a format specifier in an f-string to accomplish the same.

    [f'{int(d):04}' for d in x]
    # ['0003', '0015', '0161', '0002', '4113', '0026', 
    #  '1141', '0000', '0005', '0002', '0064']
    

    Or without the intermediate conversion to an int.

    [f'{d:>04}' for d in x]
    # ['0003', '0015', '0161', '0002', '4113', '0026', 
    #  '1141', '0000', '0005', '0002', '0064']