0

For a task in school we have to develop a programme that will take a piece of text from the user turn this to a list and then find all positions of a word that the user has searched for within the text.

I have found multiple ways to nearly do this but they all have a slight downfall somewhere along the line. Apart from one but this has one line I do not understand and therefore I was wondering if anyone could explain this to me.

The line of code is position = [I for I, x in enumerate(text2) if x == (word)]

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
  • 1
    This is a [list comprehension](http://www.secnetix.de/olli/Python/list_comprehensions.hawk) that uses [`enumerate`](https://docs.python.org/3/library/functions.html#enumerate) – Patrick Haugh Jan 18 '17 at 19:53
  • position is a list of all indices where an element of text2 equals word – fafl Jan 18 '17 at 19:57

1 Answers1

0

The enumerate function creates the indices corresponding to the position of an element in a sequence.

So if you have the list l = ['this', 'is', 'a', 'text'], enumerate would generate [(0, 'this'), (1, 'is'), (2, 'a'), (3, 'text')] (actually it creates a generator, but that's not really important for now). According to the python docs, enumerate is equivalent to:

def enumerate(sequence, start=0):
    n = start
    for elem in sequence:
        yield n, elem
        n += 1

The tuples are then unpacked into I, x. If x is equal to the word, I is added to the list.

Nynq
  • 26
  • 2