Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Regular Expressions

I'm a little confused on the difference between re.finditer() and re.findall(). Can someone please explain it to me?

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,441 Points
  • re.findall returns a list of resultant strings. This runs to completion before returning results.

  • re.finditer returns an iterable that returns match objects. This stops scanning text until next result is requested.

More info in the docs

>>> import re
>>> for x in re.findall(r"\w+", "a bb ccc dddd eeeee"):
...     print(x)
... 
a
bb
ccc
dddd
eeeee
>>> for x in re.finditer(r"\w+", "a bb ccc dddd eeeee"):
...     print(x)
... 
<_sre.SRE_Match object at 0x116423b90>
<_sre.SRE_Match object at 0x116423cc8>
<_sre.SRE_Match object at 0x116423b90>
<_sre.SRE_Match object at 0x116423cc8>
<_sre.SRE_Match object at 0x116423b90>
>>> re.findall(r'\w+', 'a bb ccc dddd eeeee')
[a, bb, ccc, dddd, eeeee]
>>> for x in re.finditer(r'\w+', 'a bb ccc dddd eeeee'):
...     print(x.group())
... 
a
bb
ccc
dddd
eeeee

Post back if you need more help. Good luck!!!