Mongo Masood
Mongo Masood

Reputation: 27

How to print the distance between strings in the list

I want to print the distance between Strings in a list.

For example, if my list contains like below, I would like to know the distance from Deer to Crazy, but Deer can be anywhere in the list and Crazy can come before or after the Deer in the list.

['black', 'white', 'Deer', 'Blue', 'More', 'Crazy']

Upvotes: 1

Views: 230

Answers (3)

fuad ashraful
fuad ashraful

Reputation: 24

Try this code:

myList=['black', 'white', 'Deer', 'Blue', 'More', 'Crazy']

idx1=0
idx2=0 

if 'Deer' in myList:
    idx1=myList.index('Deer')

if 'Crazy' in myList:
    idx2=myList.index('Crazy')


print('differnce is {}'.format(idx2-idx1))

Upvotes: -3

saibhaskar
saibhaskar

Reputation: 467

Do you mean to print number of elements better your strings?

If yes I think the solution is: print(list.index(element1)-list.index(element2))

In your case it is :print(list.index("Deer")-list.index("Crazy"))

Upvotes: 0

Selcuk
Selcuk

Reputation: 59444

Use the list.index() method:

>>> my_list = ['black', 'white', 'Deer', 'Blue', 'More', 'Crazy']
>>> abs(my_list.index('Deer') - my_list.index('Crazy'))
3

Upvotes: 4

Related Questions