Piyush Divyanakar
Piyush Divyanakar

Reputation: 241

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

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.

Upvotes: 3

Views: 2658

Answers (4)

l'L'l
l'L'l

Reputation: 47169

I think you should consider extend():

>>> a = [1, 2, 3]
>>> a.extend([4, 5, 6])
>>> a
[1, 2, 3, 4, 5, 6]

Both + and += operators are defined for list, which are semantically similar to extend.

list + list2 creates a third list in memory, so you can return the result of it, but it requires that the second iterable be a list.

list += list2 modifies the list in-place (it is the in-place operator, and lists are mutable objects, as we've seen) so it does not create a new list. It also works like extend, in that the second iterable can be any kind of iterable.

Time Complexity

  • Append has constant time complexity, O(1).
  • Extend has time complexity, O(k).

Iterating through the multiple calls to append adds to the complexity, making it equivalent to that of extend, and since extend's iteration is implemented in C, it will always be faster if you intend to append successive items from an iterable onto a list.

More Information

Upvotes: 3

Reblochon Masque
Reblochon Masque

Reputation: 36662

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])

Upvotes: 4

sachin dubey
sachin dubey

Reputation: 779

You have got short answer from Jeevaa and Reblochon Masque but if you want to use for loop then try this:

a = [5,6]
b = [1,2,3]
for val in b[::-1]:#Reverse b and insert it to a
   a.insert(0,val)
print(a)

Output

[1,2,3,5,6]

Upvotes: 1

jeevaa_v
jeevaa_v

Reputation: 423

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

or

>>> a = [1, 2, 3]
>>> a += [4, 5, 6]
>>> a
[1, 2, 3, 4, 5, 6]

Upvotes: 1

Related Questions