Elgin Beloy
Elgin Beloy

Reputation: 93

What do two parameters do in a ".append" in Python?

I know this is basic but google is not helping. I'm currently trying to translate some python to java and I came across list.append([x][i]). No , no nothing. Just like that. Can anyone explain what x, and i represent in this .append

Example:

from math import log

def number_of_steps(weight):
    return int(log(weight * 2, 3)) + 1


def instruction_index(n, weight):
    offset = (3 ** n - 1) / 2

    corrected = int((weight + offset) / 3 ** n)

    return corrected % 3


def answer(weight):
   instructions = []

    steps = number_of_steps(weight)

    for n in xrange(steps):

    i = instruction_index(n, weight)

    instructions.append(['-', 'R', 'L'][i])

    return instructions

Upvotes: 0

Views: 533

Answers (2)

Metalfreak
Metalfreak

Reputation: 149

It creates a list from the variable x and appends its value at the the index i to the original list.

Upvotes: 0

Andre Pastore
Andre Pastore

Reputation: 2897

  1. It is creating a single list [x] with element x;
  2. Then, it is accessing element under index i of array.

Following code try to expand this syntax:

l = [x]
list.append(l[i])

I don't know nothing about the context of call, if it is inside a loop or something. If you can edit you post with context, it may clarify us.

On your real code, it happens on line:

instructions.append(['-', 'R', 'L'][i])

In this case, depending on the value of i, it will return -, R or L, or a invalid index error in the case of i is greater than array length (not in this application, because it is calculated based on 3).

Upvotes: 3

Related Questions