Street Soldier
Street Soldier

Reputation: 11

Do something after checking if 2 elements in one list are the same

I wanted to know, how to check whether or not 2 elements in one list are the same. The list is going to be an user input. We loop through the list to print out the index positions of each word inputted. If we come across the same word again in the same input, when we print out the, first user-inputted sentence, as indexes of the actual words (no punctuation), I want my program to display the first index of the same word.

For eg:-

USERINPUT - I like to code because i like it and i like it a lot

There are 14 words. Only 9 are different. So the final output of my program should print their index positions - (+1) - Since python starts indexing from 0 onwards. The final result of the program should be:-

1 2 3 4 5 1 2 6 7 1 2 6 8 9

Upvotes: 0

Views: 131

Answers (2)

Ben Stobbs
Ben Stobbs

Reputation: 424

You could use the index() list method:

firstsentence = input('Enter a sentence: ')
firstsentence = firstsentence.lower()
words = firstsentence.split(' ')

s = ""

for word in words:
    s += str(words.index(word)+1) + " "

print(s)

Upvotes: 1

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48067

You may do it like:

my_string = "I like to code because i like it and i like it a lot"

# Convert string to lower-case alphabets
my_string = my_string.lower()

# list of words in sentence
my_word_list = my_string.split()

# List to maintain unique words with index
unique_list = []
for word in my_word_list:
    if word not in unique_list:
        unique_list.append(word)

#                Find index of word in list + 1  v
my_indexes = ' '.join(str(unique_list.index(word)+1) for word in my_word_list)

Final value hold by my_indexes will be:

'1 2 3 4 5 1 2 6 7 1 2 6 8 9'

Upvotes: 0

Related Questions