Electric Electric - 2 years ago 94
Python Question

Using pop on a list containing a string

I have a list:

listA = ['1,2,3,4,5']

where it is in string format. I want to perform a simple function that removes the last digit in the string, which in this case would be 5 and print it out.

I've tried something

listA = ['1,2,3,4,5']
for i in listA:

What i tried is wrong as I'm not familiar with using pop on strings.

Answer Source
  1. What you have is not a list of integers. It is a list with a single element, that element is a string of comma separated integers

  2. You're not using i

  3. You're iterating over the list and mutating it as you do so. Do not do this, because it does not give you the behaviour you expect.

I would recommend a while loop instead. First, fix your array.

listA = listA[0].split(',')

Now, iterate over it.

while listA:

You use the truthiness of a nonempty list to keep iterating over it. This removes all the digits. However, if you just want the last digit and nothing more, call listA.pop() only once.

If you don't want to fix your array, you should extract the last digit like this:

 listA = ['1,2,3,4,5']
 print(int(listA[0][-1]))  # [0] gets the string, [-1] gets the last character in the string

This is ungainly, so I recommend fixing your array instead.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download