0

Im trying to append 2 arrays using python classes.

    def __init__(self):
        self.inArray = [0 for i in range(10)]
        self.count = 0

    def get(self, i):
        return self.inArray[i]

    def set(self, i, e):
        self.inArray[i] = e

    def length(self):
        return self.count

    def append(self, e):
        self.inArray[self.count] = e
        self.count += 1
        if len(self.inArray) == self.count:
            self._resizeUp()     # resize array if reached capacity

    def insert(self, i, e):
        for j in range(self.count,i,-1):
            self.inArray[j] = self.inArray[j-1]
        self.inArray[i] = e
        self.count += 1
        if len(self.inArray) == self.count:
            self._resizeUp()     # resize array if reached capacity

    def remove(self, i):
        self.count -= 1
        val = self.inArray[i]
        for j in range(i,self.count):
            self.inArray[j] = self.inArray[j+1]
        return val

    def __str__(self):
        return str(self.inArray[:self.count])

    def _resizeUp(self):
        newArray = [0 for i in range(2*len(self.inArray))]
        for j in range(len(self.inArray)):
            newArray[j] = self.inArray[j]
        self.inArray = newArray

    def appendAll(self, A):

        self.ls = [2,3,4,5]
        ls = ls.append(A)

Im trying to write a function appendAll(self,A) that appends all elements of the array A in the array list (the one represented by self). For example, if ls is [2,3,4,5] then ls.appendAll([42,24]) changes ls to [2,3,4,5,42,24].

This is all I can think of doing but I'm just stuck, any help will be appreciated

Hassan
  • 39
  • 6

2 Answers2

0

You can use extend( Have a look at What is the difference between Python's list methods append and extend? )

ls = ls.extend(A)

in your code :

def appendAll(self, A):
    self.ls = [2,3,4,5]
    self.ls = self.ls.extend(A)
PilouPili
  • 2,601
  • 2
  • 17
  • 31
Mert Köklü
  • 2,183
  • 2
  • 16
  • 20
0

You can also just do like so (Basically just like extend).

ls += A

your code:

1. def appendAll(self, A):
2.    self.ls = [2,3,4,5]
3.    ls = ls.append(A)

The append function does not return a list it operates on the original list.

the append function is also not what you are looking for,
because this will happen:

[2, 3, 4, 5, [42, 24]]

but extend will look like so:

[2, 3, 4, 5, 42,24]

Remember! both functions do not return a new list
they simply operate on the given list.

Amir Kedem
  • 68
  • 1
  • 9
  • How would I try to test this out, because when i write ls.appendAll() im not sure what to put in parameters – Hassan Oct 27 '19 at 22:37
  • Try this out and play with it a little through the console and get a feeling of what is actually happening. I'm sure there is a lot of great tutorials out there too. Good Luck :) – Amir Kedem Oct 27 '19 at 22:40