0

I have a function that returns an array of info it can return an empty array I use a _ as a reference to an empty array is this appropriate.

_ = []

lines = Func() #will come out like ["abc","def","etc"] or []

if lines != _ :
    ...
    ...
    ...

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
  • What purpose would the naming convention `_` serve? Seems overly complex. Also, you can test whether an array-like object is empty using something like: `if lines: ...` This basically tests the "truthiness" of the object. – blacksite Dec 16 '21 at 23:24
  • What do you mean by "appropriate"? Please read https://stackoverflow.com/help/dont-ask - we don't deal in matters of opinion here. A question like this is (at least, as far as I can tell) only on topic if you think you have a performance consideration, or a specific concern about messing something up later down the road. – Karl Knechtel Dec 16 '21 at 23:28
  • This is very unidiomatic in at least a couple of ways. Conventionally, a variable with the name `_` is used to indicate that the *variable will not be used*. For example, sometimes you want to repeat something `n` number of times, so you could use a loop `for _ in range(n): do_something()`. Also, generally if you are testing if a list is empty or not, you want to use `if lines: ...` instead of explicitely using `!= []` – juanpa.arrivillaga Dec 16 '21 at 23:41

1 Answers1

1

Nitpick: Python has lists not "arrays". If you want to use [] then simply use it as is. Don't create variables for such a thing, that's anti-idiomatic and error prone. Furthermore, _ should only be used when you don't care about the value.

If you want to check if a list is empty you can do so in different more idiomatic ways than comparison with an empty list:

if lines: # lists are "truthy" when not empty
   ...

if len(lines) > 0:
   ...
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128