Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a slice equivalent to "append" in Python?

Tags:

python

To prepend to a list, I use the_list[0:0]. But with slice appending:

  • [-0:-0] doesn't work.
  • [::-1][0:0] doesn't work.
  • And obviously [-1:-1] won't work.
  • [len(the_list), len(the_list)] doesn't count -- looking for just numbers here

Example:

results = [3,1,0]
results[-1:-1] = [3]
print(results)

>>> [3,1,3,0]

results[-0:-0] = 5
print(results)

>>> [5,3,1,3,0]

results = [3,1,0]
results[-1:-1] = [3]
print(results)

>>> [3,1,3,0]

results[-0:-0] = 5
print(results)

>>> [5,3,1,3,0]

Thoughts?

like image 395
Aaron Bell Avatar asked Jul 27 '26 02:07

Aaron Bell


1 Answers

The slice that starts after the last element is len(…):.

results[len(results):] = [3]

but why, when there are += and extend?

results += [3]
results.extend([3])
like image 183
Ry- Avatar answered Jul 28 '26 16:07

Ry-



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!