-3

so i just started learning python and found this 2 lines of code for finding multiple indexes of letters in strings/lists. I'd love if some of you guys can simplify the 2nd line for me,

text= 'Allowed Hello Hollow'
print [n for n in xrange(len(text)) if text.find('ll', n) == n]

I don't know if it's just a shortcut style writing or something, but I'd like it simplified, thanks :D

Alon Mazor
  • 31
  • 2
  • Maybe try deconstructing the list comprehension (the `[n for n in ...]` part) into a `for` loop and see how it goes? –  Nov 17 '17 at 23:46
  • `l = []; for n in xrange(len(text)): if text.find('ll', n) == n: l.append(n);` then `print l` – davedwards Nov 17 '17 at 23:46
  • You should seriously consider learning Python 3, Python 2 will reach its official End Of Life in 2020. – PM 2Ring Nov 18 '17 at 05:51

1 Answers1

0

Here's the "simplified" version

myList = []
for n in xrange(len(text)) : 
    if(text.find('ll', n) == n) : 
        list.append(n)
print myList

This answer explains the syntax

Kays Kadhi
  • 344
  • 5
  • 14
  • I think you have an error. `xrange` is for python 2 but `print()` is for python 3. Make the code for python 2 or 3, but not something hybrid. – Ender Look Nov 18 '17 at 00:01
  • @EnderLook You can use parentheses with the `print` statement. – cs95 Nov 18 '17 at 00:04
  • @cᴏʟᴅsᴘᴇᴇᴅ, oh, I didn't know that. – Ender Look Nov 18 '17 at 00:05
  • @cᴏʟᴅsᴘᴇᴇᴅ Yes, you can use parentheses with the `print` statement, but it makes the code confusing, since the `print` _statement_ with parentheses prints a tuple, so it's rather different to calling the `print` _function_. However, in Python 2.6+ the `print` function is available via a future import: just put `from __future__ import print_function` as the first `import` statement of the script. – PM 2Ring Nov 18 '17 at 05:47
  • BTW, you shouldn't use `list` as a variable name because that shadows the built-in `list` type. And you shouldn't do `print(some_stuff)` unless you're actually calling the print _function_. – PM 2Ring Nov 18 '17 at 05:50