Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use list slicing to append to end of list in python?

Tags:

python

list

slice

Following can be used to add a slice to append to front of list.

>>> a = [5,6]
>>> a[0:0] = [1,2,3]
>>> a
[1,2,3,5,6]

what slice to use to append to the end of list.

like image 732
Piyush Divyanakar Avatar asked Jan 17 '26 05:01

Piyush Divyanakar


1 Answers

If you really want to use slice, you can use the length of a:

a = [5, 6]
a[len(a):] = [1, 2, 3]
a

output:

[5, 6, 1, 2, 3]

But the simplest is to directly extend a:

a = [5, 6]
a += [1, 2, 3]   # or a.extend([1, 2, 3])
like image 141
Reblochon Masque Avatar answered Jan 19 '26 17:01

Reblochon Masque



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!