0

what's the python equivalent of the JS

const arrayWithMyNewItem = [mynewitem, ...existingarray]
John
  • 4,786
  • 8
  • 35
  • 44
  • 2
    `new_array = [item] + old_array`? – Nathaniel Ford Oct 28 '21 at 19:05
  • the above addresses the question but I did not see @NathanielFord expression which is actually what I was looking for – John Oct 28 '21 at 19:09
  • https://stackoverflow.com/a/10892614/1659569 found it here – John Oct 28 '21 at 19:10
  • 1
    I suspect the problem is that the question as written is not the same as the question you meant to ask. That expression doesn't prepend to an array. Instead, it creates a new array constructed such that its items appear as they would have had you actually done a prepend on the original array. – Ouroborus Oct 28 '21 at 19:20
  • It is a prepend, in that it puts the element on the front of the array. It's the idiomatic way in python, and while it creates a new array, that is also effectively true of javascript as well. O(n) where `n` is the size of the new list. – Nathaniel Ford Oct 28 '21 at 20:05
  • 2
    destructuring is called unpacking in python and uses a star for lists instead of 3 dots. i.e. ```arrayWithMyNewItem = [mynewitem, *existingarray]``` – byteface Oct 28 '21 at 21:18
  • I renamed the question: @byteface thanks for that, I guess that's exactly what I was looking for – John Oct 29 '21 at 08:15

0 Answers0