0

I came across some code in python which I am unable to understand completely.

[func([t.string]) for t in textList]

where textList is a list of html tag enclosed text. What it does and how is it different from this?

for t in textList
    func(t.string)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
ptntialunrlsd
  • 794
  • 8
  • 23
  • The list comprehension results in a new list with the return values of each `func()` call. – Martijn Pieters Dec 29 '14 at 22:28
  • So, disregarding the return value, does both the syntaxes return in the similar function call? – ptntialunrlsd Dec 29 '14 at 22:33
  • You can't disregard the return value, that's the *whole point* of the list comprehension. Your own loop version doesn't pass in a list with one element, you'd have to call `func([t.string])` like the original. – Martijn Pieters Dec 29 '14 at 22:34
  • To fully reproduce what the list comprehension syntax does you'd need to add a line above your loop: `result = []`, then use `result.append(func([t.string]))` as your loop body. `result` would then end up being the same list as what the list comprehension produces. – Martijn Pieters Dec 29 '14 at 22:38

0 Answers0