Home > other >  TypeError: list.append() takes exactly one argument (2 given) error when appending array through ite
TypeError: list.append() takes exactly one argument (2 given) error when appending array through ite

Time:07-07

i want my code to find the position of capital letters and add them to an array. After testing, i get the error: TypeError: list.append() takes exactly one argument (2 given) also when testing with a input with a singular capital letter it works fine, however when they are multiple capital letters, the array will only contain the last position.

for i in range(0,length):
    letter = camel_case[i]

    for k in range(0,25):
        check = capitals[k]

        if  check == letter:
            position = i
            print(f"{position}")

            global caps

            caps = []
            
            caps.append(capital_quantity,i)
            capital_quantity = capital_quantity   1


        else:
            pass

CodePudding user response:

The error is self-explanatory. The append function only takes a single parameter but two were passed.

Replace the following line of code:

caps.append(capital_quantity,i)

with this:

caps.append(capital_quantity)

CodePudding user response:

For lists, you can only append one item at a time. If you would like to keep capital_quantity and i together you could append them to your list as a secondary list i.e.

caps.append([capital_quantity,i])

Its worth noting, if for whatever reason you want to add both values to your list in a flat structure rather than a nested list you could use the.extend() method. This is a good tutorial to understand the behavior.

CodePudding user response:

Seems like you got list.append and list.insert mixed up.

list.append takes in one argument to add to the end of the list, whereas list.insert takes both a positional argument and the item to insert in that position of the list.

Additionally, there appears to be other bugs/fixes in your code.

  1. range(0,25) should be range(0,26) since the last item in the range will be one less than the end argument (numbers 0-24 instead of 0-25)
  2. caps=[] sets the list caps to an empty list every time it's called. I don't think that's what you want.
  3. You don't need the else:pass
  4. You don't need the capital_quantity. Just use list.append. If you need to count how many capitals are in the list, just do len(caps)

Here's how I'd implement this problem the most straightforward way:

caps=[]
for i,c in enumerate(camel_case):
    if c.isupper():
        caps.append(i)

We check if each character c in the string camel_case is uppercase, and if it is, we append its index i to the list.

  • Related