How does this code work? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How does this code work?

def print_everything(*args): for count, thing in enumerate(args): print( '{0} - {1}'.format(count, thing)) print_everything('apple', 'banana', 'cabbage') It prints 0-apple 1-bannana .... But how thing is defined but count is not args contains only things and what's this enumerate (args)

8th Jan 2020, 3:58 AM
Pattern
Pattern - avatar
1 Answer
+ 1
*args parameter contains all the unnamed (non-keyword) arguments passed to the function. In this case 3 strings are passed, so args is a tuple of 3 strings. enumerate() function produces a tuple from each element of the sequence, which contains the index number (by default starting with 0) and the element itself. So in the first iteration, enumerate produces (0, 'apple') This tuple is unpacked to the two variables (count, thing) so they can be used individually for printing.
8th Jan 2020, 4:20 AM
Tibor Santa
Tibor Santa - avatar