3

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.

  • 1
    Examples of replacing `list` methods with slicing are [given in the tutorial for many methods](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists). – ShadowRanger Nov 30 '17 at 06:14

4 Answers4

4

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])
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
  • But isn't the slice method faster compared to += – Piyush Divyanakar Nov 30 '17 at 06:15
  • @PiyushDivyanakar: The `+=` is basically guaranteed to be faster (slicing operations involve temporary `list` objects, and the surprisingly expensive `len` call). `+=` is more readable, and the fastest option available. – ShadowRanger Nov 30 '17 at 06:18
  • @ShadowRanger: Although if it's a non-local variable `extend()` is probably better. https://stackoverflow.com/a/24261311/499581 – l'L'l Nov 30 '17 at 06:35
  • 1
    @l'L'l: True, though on Py3, you can explicitly declare the variable `nonlocal` and `+=` will work. Cases where it still won't work include when the `list` in question is part of a `tuple`; `mytuple = ([], []); mytuple[0] += [1,2,3]` is an error, while calling `extend` is fine (because it doesn't attempt to reassign `mytuple[0]`). – ShadowRanger Nov 30 '17 at 11:57
3

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

l'L'l
  • 44,951
  • 10
  • 95
  • 146
1
>>> 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]
jeevaa_v
  • 423
  • 5
  • 14
1

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]
sachin dubey
  • 755
  • 9
  • 28