0

I have converted items in a list to a string using the following:

target_ls = [w, x, y, z]

    as_str = (str (y) for y in target_ls)

    final_str = "\t".join(as_str) + "\n"

But I notice that I can also use:

as_str = [str (y) for y in target_ls]
final_str = "\t".join(as_str) + "\n"

The result for both is the same. Does using square brackets instead of parentheses (or vice-versa) matter in this case?

Thank you

  • what are `w, x, y, z`? please take the [tour](http://stackoverflow.com/tour), read up on [how to ask a question](https://stackoverflow.com/help/asking) and provide a [minimal, complete and verifiable example](https://stackoverflow.com/help/mcve) that reproduces your problem. – hiro protagonist Oct 24 '18 at 10:19

2 Answers2

1

when you write as_str = [str (y) for y in target_ls] it creates a list and keep in memory but as_str = (str (y) for y in target_ls) is a generator, so it will not keep anything in memory once you iterate over it, it will do a 'lazy execution' and give you the desired result.

Generators are memory efficient but can be used only once.

ansu5555
  • 416
  • 2
  • 7
0

Brackets allocate a new list. In case you have many elements, this will allocate a lot of memory needlessly; use parentheses.

Parentheses create a generator. A generator can be used only once; if you need to reuse as_str again, use brackets.

Amadan
  • 191,408
  • 23
  • 240
  • 301