HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Find position of a word in a list in Python

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
positionwordpythonfindlist

Problem

The aim of this program is to say which position a word is in a list. This is just a basic version of it. I made to see if I could shorten it more than what it is currently.

position, word, word_list = 0, 'hello', 'hello what is your name i am bob this is a sentence a very n ice sentence'
word_list = word_list.split(" ")
print(word_list)
if word in word_list:
    for name in word_list:
        position = position + 1
        if word == name:
            print('your word is in the list at ',position)
else:
    print('Your word is not in the sentence')

Solution

A similar solution using enumerate():

word, word_list = 'hello', 'hello what is your name i am bob this is a sentence a very n ice sentence'

if word in word_list:
    for position, name in enumerate(word_list):
        if name == word:
            print("Your word is in the list at ", position)
else:
    print('Your word is not in the sentence')


You could also use a list comprehension:

word, word_list = 'hello', 'hello what is your name i am bob this is a sentence a very n ice sentence'

positions = [x for x, n in enumerate(word_list).split() if n == word]
if positions:
    for position in positions:
        print('your word is in the list at ', position)
else:
    print('Your word is not in the sentence')


Also, a generator expression that's a little more efficient:

word, word_list = 'hello', 'hello what is your name i am bob this is a sentence a very n ice sentence'

found = False
for position in (x for x, n in enumerate(word_list) if n == word):
    print('your word is in the list at ', position)
    found = True
if not found:
    print('Your word is not in the sentence')

Code Snippets

word, word_list = 'hello', 'hello what is your name i am bob this is a sentence a very n ice sentence'

if word in word_list:
    for position, name in enumerate(word_list):
        if name == word:
            print("Your word is in the list at ", position)
else:
    print('Your word is not in the sentence')
word, word_list = 'hello', 'hello what is your name i am bob this is a sentence a very n ice sentence'

positions = [x for x, n in enumerate(word_list).split() if n == word]
if positions:
    for position in positions:
        print('your word is in the list at ', position)
else:
    print('Your word is not in the sentence')
word, word_list = 'hello', 'hello what is your name i am bob this is a sentence a very n ice sentence'

found = False
for position in (x for x, n in enumerate(word_list) if n == word):
    print('your word is in the list at ', position)
    found = True
if not found:
    print('Your word is not in the sentence')

Context

StackExchange Code Review Q#125312, answer score: 2

Revisions (0)

No revisions yet.