Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python

I am having a hard time understanding why this is...

turtles = [ "Michelangelo", "Leonardo", "Raphael", "Donatello", ]

def shredder(names): if len(names) >= 1: names[0] = "Bebop"

shredder(turtles)

for turtle in turtles:

I know this equals: Bebop Leonardo Raphael Donatello

But i am not sure why bebop replaces the 1st one or 0 lol

1 Answer

Eric M
Eric M
11,517 Points

Hi Christopher,

There's a few things going on here, but it sounds like you're just asking for clarity on the shredder() function. I've added some comments to all of the code that might also help.

# create a list of names and populate it with 4 items
turtles = ["Michelangelo", "Leonardo", "Raphael", "Donatello"]

# a function that takes a list and replaces the first item if the list
# has more than one item already
def shredder(names):
        if len(names) >= 1:
                names[0] = "Bebop"

# run the shredder function on the turtles list
shredder(turtles)

# loop through the turtles list, printing each item
for turtle in turtles:
        print("* " + turtle)

The shredder() function has a parameter names. When we call this function we provide an argument during the function call, this is then referred to by the paramter name within the function. In this code we pass turtles as the argument, and the first statement is a conditional statement that checks its length. The turtles list has a length of 4, so it meets the if len(names) >= 1 condition. This if branch then executes names[0] = "Bebop" replacing the list item at index 0 with "Bebop".

Cheers,

Eric

ahhhhhh okay PERFECT!!! Makes total sense now! Thank you so much!!