Home > Mobile >  How to change the below for loop code to a faster way,for example without a loop?
How to change the below for loop code to a faster way,for example without a loop?

Time:03-24

I was using a for a loop to create from A0 to A49 and is saved to a list .Code below

A = []
B = []
C = []   
for i in range(50):
    a = 'A\_%d' % i  
    b = 'B\_%d'%i  
    c = 'C\_%d'%i  
    A.append(a)  
    B.append(b)  
    C.append(c)

How can i do this without for loop?

I want to improve the above code.

Since I am not good at programming. I want to improve my skills by looking into different approaches for the same.

CodePudding user response:

If I'm not mistaken you want an output like this:

['A0', 'A1', 'A2', ... , 'A49', 'A50']

and all this without a separate for loop. It is fairly easy to do so with the help of List Comprehension, this is a lesser-known way for beginners but is very useful. Say for example you want to store values in a list ranging from 0 to 9. You can do this in two ways:

  1. First way is using a separate for loop.
lst = list()
for i in range(10):
    lst.append(i)

This will add the values from 0 to 9 to the List lst.

  1. Second way is relatively easy and less time-consuming, using List Comprehension.
lst = list(i for i in range(10))

This will comprehend all the values over which i is iterating to the List lst saving lines of code, and this is what you asked for as well if I am not mistaken. This method declutters your code as well as improves it.

So the formatted code will look something like this (You can modify as per your needs):

A = list(f"A{i}" for i in range(50))

Hope my answer helps. :)

You can refer to this article for more clarification if you need: Python - List Comprehension

Edit 1: Removed the part pointing out the errors. You have already edited the error part of the question, your code is error free.

Edit 2: Removed unnecessary backslash

  • Related