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 trialChristopher Morris
iOS Development with Swift Techdegree Student 1,760 PointsI 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:
print("* " + turtle)
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
11,545 PointsHi 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
Christopher Morris
iOS Development with Swift Techdegree Student 1,760 PointsChristopher Morris
iOS Development with Swift Techdegree Student 1,760 Pointsahhhhhh okay PERFECT!!! Makes total sense now! Thank you so much!!