Andela Bootcamp: Day 3 (“Do you want **kwargs with that?”)

I know what you’re thinking. “What in the heck are ‘kwargs’??” That was my reaction too. They happen to be my new learn for today. Kwargs means ‘KeyWord ARGumentS. Apologies if i get a bit nerdy today.

So, when you have a function that sums two numbers, it might basically looks like this:

def add(a, b):
return a + b

But what if you want to sum, say, 500 numbers? Or whoever ends up using your function wants to sum more than two numbers? Here, you can use *args, like so:

def add(*args):
total = 0
for i in args:
total += i
return total

What the code above does is basically loop through all the numbers passed in the argument, and adds them to the variable total. Now, what if you have a CSV file that has 100 entries of, say, names and phone numbers of people, and you want to print them out. It would be very tiresome to do that manually. So, instead, you could use this method:

def list_of_people(**kwargs):
return kwargs['name'], kwargs['phone_number']

So, if you have a list of key-value pairs (a list of dictionaries) that you pass to the function above, it will print out the key-value pairs.

Points to note:

  • When using *args, the function is called like so:
a = 1, 2, 3, 4, 5

The asterisk before a (*), takes the values of a and ‘unpacks’ them into the function one by one.

  • When using **kwargs, the function is called like so:
people = [
{‘name’:’Joe’, ‘age’:45},
{‘name’:’Jo’, ‘age’:5},
{‘name’:’Joey’, ‘age’:12}

The two asterisks before people (**), take the key-value pairs and unpack them into the function.

  • The names of *args and **kwargs are not keywords. It’s just a naming convention. Calling them *number and **dictionary will work perfectly fine.

Anyway, all that coding aside, today was a good day. I talked to about 7 new people (I know, I know; round of applause for me), I learnt how to play pool, and overall, I had loads of fun.

Thursday, come at me!

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.