How do I count the distance between strings in a list?

C

collin

For example, if I were to have the code

randomlist = ["1", "2", "3", "4"]

And I want to count the distance between strings "1" and "4" which is
3, what command can I use to do this?
 
J

Jonathan Gardner

For example, if I were to have the code

randomlist = ["1", "2", "3", "4"]

And I want to count the distance between strings "1" and "4" which is
3, what command can I use to do this?

You'd have to get the indexes of the two items and subtract them.
There is an 'index' method on the List object for that.
 
S

Steven D'Aprano

For example, if I were to have the code

randomlist = ["1", "2", "3", "4"]

And I want to count the distance between strings "1" and "4" which is 3,
what command can I use to do this?

This question is ambiguous. It could mean:

int("4") - int("1")
=> 3

ord("4") - ord("1")
=> 3

randomlist.index("4") - randomlist.index("1")
=> 3


and possible more as well. Perhaps you should explain what you want to
do. What do you mean by "distance between strings", and is it important
that they are in a list?
 
K

Ken Seehart

collin said:
For example, if I were to have the code

randomlist = ["1", "2", "3", "4"]

And I want to count the distance between strings "1" and "4" which is
3, what command can I use to do this?
randomlist.index("4") - randomlist.index("1")

Ken
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,007
Latest member
obedient dusk

Latest Threads

Top