Paul Erlenmeyer
Paul Erlenmeyer

Reputation: 521

Are Python arrays the same as in Java?

I have an assignment in my class to implement something in Java and Python. I need to implement an IntegerStack with both languages. All the values are supposed to be held in an array and there are some meta data values like head() index.

When I implement this is Java I just create an Array with max size (that I choose):

public class IntegerStack {
    public static int MAX_NUMBER = 50;
    private int[] _stack;
    private int _head;

    public IntegerStack() {
        _stack = new int[MAX_NUMBER];
        _head = -1;
    }

    public boolean emptyStack() {
        return _head < 0;
    }

    public int head() {
        if (_head < 0)
            throw new StackOverflowError("The stack is empty."); // underflow

        return _stack[_head];
    }
    // [...]
}

I'm really not sure how to do this in Python. I checked out a couple tutorials, where they all say that an array in python has the syntax my_array = [1,2,3]. But it's different, because I can use it as a List and append items as I want. So I could make a for loop and initiate 50 zero elements into a Python array, but would it be the same thing as in Java? It is not clear to me how a Python List is different from an Array.

Upvotes: 1

Views: 2061

Answers (5)

monomonedula
monomonedula

Reputation: 644

Fist of all, you need to distinguish between arrays and lists in Python. What you are talking about here is list class, but there are actual arrays and they are more or less the same as arrays in Java.

Python's list is similar to Java's ArrayList and to C++'s std::vector.

In other words, you have three possible solutions here:

  1. Use simple list and just append elements to it.
  2. Use python's arrays that are the closest thing to Java's arrays.
  3. Use python's deque.

Regarding the use of list, if your goal is to initialize it with N empty elements, what you can do is:

N = 10     # or any other number
my_list = [0] * N # 0 is the element here for the list to be filled with

or little more fancy approach

from itertools import repeat
my_list = list(repeat(0, N))

Upvotes: 3

Holgerillo
Holgerillo

Reputation: 46

If you want to implement something close to your java version, you could use a numpy array by importing numpy. Numpy arrays are similar because they are immutable objects like in java. Then you could write in your constructor:

    _stack = np.zeros(MAX_NUMBER)

Otherwise you could use the mutable list object from python itself, in this case the list is already a stack essentially as you can see in the python docs for data structures:

The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append(). To retrieve an item from the top of the stack, use pop() without an explicit index. For example:

    >>> stack = [3, 4, 5]
    >>> stack.append(6)
    >>> stack.append(7)
    >>> stack
    [3, 4, 5, 6, 7]
    >>> stack.pop()
    7
    >>> stack
    [3, 4, 5, 6]
    >>> stack.pop()
    6
    >>> stack.pop()
    5
    >>> stack
    [3, 4]

The first version is more performant however, because mutable python objects have to be copied everytime they are changed whereas immutable objects are just created and old objects with no names referring to it are garbage collected.

Upvotes: 1

Jorge F. Sanchez
Jorge F. Sanchez

Reputation: 341

This is the same code from Java to Python:

class IntegerStack:
    def __init__(self):
        self._stack = []
        self._head = -1

    def emptyStack(self):
        return self._head < 0

    def head(self):
        if self._head < 0:
            raise Exception("The stack is empty.")
        return self._stack[self._head]

Upvotes: 0

Sav
Sav

Reputation: 656

It's easer to use collections.deque for stacks in python.

from collections import deque

stack = deque()
stack.append(1) # push
stack.append(2) # push
stack.append(3) # push
stack.append(4) # push
t = stack[-1] # your 'head()'
tt = stack.pop() # pop
if not len(stack):  # empty()
    print("It's empty")

Upvotes: -1

Vosem
Vosem

Reputation: 106

In python, if you declare an array like:

myarray = []

You are declaring an empty array with head -1, and you can append values to it with the .append() function and access them the same way you would in java. For all intents and purposes, they are the same thing

Upvotes: 1

Related Questions