Home > Back-end >  Python list comprehension when creating a list
Python list comprehension when creating a list

Time:11-07

I'm trying to generate a list of random numbers. I thought this would be a good time to use list comprehension to shorten the code. The only problem is that now I have this unused "i" variable. Is there a way to write it without needing that variable, or should I not worry about it too much?

int_list = [random.randrange(0, 50) for i in range(10)]

CodePudding user response:

You can use the _ instead which acts like a placeholder for variables you don't need either in loops

int_list = [random.randrange(0, 50) for _ in range(10)]
def print_hello():
   print("Hello")

for _ in range(10): # we don't need the value of "range(10)" in 
      print_hello   # each iteration.
    

or to ignore outputs from a function

def func(a,b):
    c = a b
    return a,b,c

a,_,c = func(2,3) # we don't need store the output "b" here, 
                  # thus we "ignore" it using the "_"
print(a) # 2
print(c) # 5

With all that said, you could aswell just use the i instead - it is just a convention using _

CodePudding user response:

TLDR - Its not something to worry about.

A list comprehension creates a function namespace for its execution, including slots for local variables. When you write

[random.randrange(0, 50) for i in range(10)]

i is a local variable that is deleted when the comprehension completes. It won't overwrite an i defined in the enclosing namespace and won't take any space after the operation is done.

Its common to use _ for variables that aren't used elsewhere. That is just a convention that makes it a little easier for people reading your code.

  • Related