1

Say I have an array of thousands of colours:

x=[blue, red, green,...]

How do I delete the last character(s) of each string so x1 would be [blu, re, gree,...]

I tried this:

x1=[]
for i in range (0,len(x)):
    x1[i]=x[i:-1]

The error I get is: list assignment index out of range

Any idea how to do this?

Jellyse
  • 839
  • 7
  • 22

5 Answers5

6

You are getting the error because x1 is an empty list. The first iteration tries to assign to x1[0] which doesn't exist hence the IndexError.

Assuming x is a list of strings a more pythonic way would be to not use any indexes at all:

x1 = [color[:-1] for color in x]
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
3

If x is a list of strings, then x[i] is a string. If you want all but the last character of that string, it is x[i][:-1].

So you can write

x1 = []
for i in range(0, len(x)):
    x1.append(x[i][:-1])

or you could shorten that to

x1 = [colour[:-1] for colour in x]
khelwood
  • 55,782
  • 14
  • 81
  • 108
1
lst = ["blue", "red", "green"]

print [i[:-1] for i in lst]
shahaf
  • 4,750
  • 2
  • 29
  • 32
1

List comprehension is the best way to solve your problem:

x = ['blue', 'red', 'green']
new_x = [color[:-1] for color in x]

But you can also achieve the result using map function:

x = ['blue', 'red', 'green']
new_x = list(map(lambda color: color[:-1], x))

I'm not sure which way is better on performance, but since nobody mention map so...

Huy Vo
  • 2,418
  • 6
  • 22
  • 43
0

The reason you got the error because of this reason IndexError: list assignment index out of range

Hence you need to use .append to get this working.

KKK
  • 1
  • 1