Home > OS >  Adding a String, to the Last Element of the List
Adding a String, to the Last Element of the List

Time:11-10

So I need to check if a string is smth and append it to the list, but if it's smth_else I need to append it to the last appended by me element of it:

arr = list()

for x in anotherList:
  if x == "y":
    arr.append(x)
  elif x == "z":
    #add x to the last element of arr[]

print(arr)

I already tried arr[len(arr)-1] = x or arr[-1] = x but this returns IndexError: list index out of range

CodePudding user response:

You need to check whether there actually is a last item before adding it:

arr = list()

for x in anotherList:
  if x == "y":
    arr.append(x)
  elif x == "z":
    if arr:
        arr[-1]  = x
    else:
        arr.append(x)

print(arr)
  • Related