0

I'm currently learning Python for work and I learnt about the spread operator. Coming form Javascript and using ES6, I figured that creating a list from an object would work in a similar fashion using the spread operator. Turns out, it does.

I asked a colleague who is proficient in Python what the best way to do it was using the following example:

my_string = 'this is a string' my_list_option_one = list(my_string) my_list_option_two = [*my_string]

Both options create the same output. He told me that the first is correct because the second is weird and no one would do that.

Later I learnt about timeit and decided to give both options a try to see which was faster. Surprisingly, the one that's not done is faster as per the screen grab below:

So why is it faster and why is it not used?

VARAK
  • 835
  • 10
  • 27
  • I seen this exact question a few days ago, trying to find the dupe... – Taku Mar 25 '18 at 10:17
  • We've had a question like this just recently, but I can't find it... so to sum it up: `list(my_string)` is more common and more readable and more backwards compatible and is the preferred choice. – Aran-Fey Mar 25 '18 at 10:18
  • Oops, sorry for the duplicate – VARAK Mar 25 '18 at 10:21
  • 2
    @VARAK No worries, that duplicate has a different way of phrasing the question. I'd recommend you not to worry about this question and let it act as a sign post for people who has the question and cannot find the duplicate. – Taku Mar 25 '18 at 10:34

0 Answers0