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

John Nguyen
John Nguyen
32 Points

Python Recursion

Lets say I wanted to make a def that takes only the first initials of a word in a list. How would I do that?

For example listName = ['Bob' , 'Joe' , Ashley'] def first_letter(listName): //returns [B,J,A]

2 Answers

William Li
PLUS
William Li
Courses Plus Student 26,868 Points

List Comprehension

def first_letter(listName):
  return [i[0] for i in listName]

But if you really want to do it in recursion

# recursive version
def first_letter(listName):
  if len(listName) == 0:   # base case
    return []
  else:
    return [listName[0][0]] + first_letter(listName[1:])  # recursive call

Seriously, list comprehension is way better here.

John Nguyen
John Nguyen
32 Points

Thank you William . That really helped me. I appreciate it !