buras12
buras12

Reputation: 11

Treating a string as a list

A novice question here

I am dealing with lists of strings of different lengths (where each string is numeric) such as

a = ['1', '5', '8', '11']

I need to evaluate the last item in each list using: a[-1] which is fine most of the time.

However, when the list has just one item which is more than 1 character in length, i have an issue:

a = ['10']

Since i am using a For loop:

for el in a:
   el[-1]..... 

el[-1] is then equal to '0' and not '10' as i need it to be

How can i overcome this?

Thanks

editing the post. Thanks folks for all the suggestions. I am sorry, but i made a complete mess of the question, did not state the problem correctly. I've got a list of lists, all of which look like a above:

mylist = [a, b, c, ....]     #a = ['1', '5', '8', '11']....

I am then executing a loop over mylist where the last element of each list points to dictionary key mygraph2.nodes[el[-1]]:

for el in mylist:
      for loop_var in mygraph2.nodes[el[-1]].neighbors:
             further code here....

I found a way around my issue, but it is not elegant.

if len(el) == 1:
    el = mylist

I forced the last element to be a list even the list 1 item long. Thanks again

Upvotes: 1

Views: 445

Answers (2)

Emin Mastizada
Emin Mastizada

Reputation: 1405

The for loop in your code will assign an element from the list a to the el variable in each loop. Type of el is string (str) and using [-1] on string objects is called String Manipulation.

If a = ['1', '5', '10']:

1. el = '1', el[-1] = '1', el[0] = '1'
2. el = '5', el[-1] = '5', el[0] = '5'
3. el = '10', el[-1] = '0', el[0] = '1'

So, you can just use the el variable instead of using [-1] on it. And if you want the last element in the list a, just use a[-1], no need for a loop.

Upvotes: 1

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20490

Just do a[-1] as that gives you the last element of the list ('10'). Doing the for loop is wrong, and it gives you a[-1][-1] when you reach the last element of the string, which is '0'. Remember that in python, a string is also treated as a list.

So if x = '10' , x[0] = '1' and x[1] = x[-1] = '0'

Also if you want the output as an integer, you can cast the output as int(a[-1])

Upvotes: 0

Related Questions