Python Tutorial: Functions and Passing Lists and Dictionaries with Simple Examples

Python Tutorial: Functions and Passing Lists and Dictionaries with Simple Examples

Python Tutorial

Python Tutorial: Functions, Passing Lists, Dictionaries with Simple Examples

In Python the differences between functions, classes and methods is often best explained with examples of code. It is also the best way to learn syntax and languages for some of us. We will start off with Functions and work into Classes which is the Object Oriented Programming (OOP) in Python over the next few posts. These are merely blueprints to run data through often times in an iterated fashion. Python is much like C in syntax minus declarations, in fact it, is written in C and interpreted in a C binary. This will be the first of a series of post that are a primer to the programming language Python. This Python tutorial will focus on functions with a refresher or start learning Python for beginners to look at lists, dictionaries / associative arrays.

Python Tutorial: Python Functions

A function is a start of code reusability in Python that we will later expand on with OOP concepts. We can call a function and pass or not pass arguments to the function.For anyone totally new to programming an example of an argument would be “ping 8.8.8.8″, 8.8.8.8 was an argument we passed to the program ping.

Python Tutorial: Function without any Arguments Example

Lets make a function and call it.

#!/user/bin/python
def sld():
    print('Slowest Common Denominator')    
sld()
#Run that and your output will be:
>>>Slowest Common Denominator

Python Tutorial: Function with a single Argument Example

Ok, that was easy enough. We made a function and called it with “sld()”, that executed “def sld()” or “called” it for execution. Next lets pass an argument to be executed in the function. This begins hitting on the reusability factor of function. We are setting up a framework or routine that can be called many times and pass different data values to it each time.

We will pass an argument to a variable in the function, in this case “name” will get the string “brent is the” as it’s value. We will then print the string in the function along with the argument we passed that is represented with the variable “name”. When you define arguments in this fashion, you have to pass as many as you define to the function or you will get a syntax error.

#!/user/bin/python
def sld(name):
    print(name +'Slowest Common Denominator')    
sld('Brent is the ')
#This time we added a placeholder "name" in the function parentheses and passed it a string.
>>Brent is the Slowest Common Denominator

If you had not passed an argument to the definition but defined one you would get this type of error.

#!/user/bin/python
def sld(name):
    print(name +'Slowest Common Denominator')    
sld('Brent is the ')
>>    sld()
TypeError: sld() takes exactly 1 argument (0 given)

Python Tutorial: Function with Multiple Arguments Example

Now let’s pass more than one variable.

#!/user/bin/python
def sld(name, tail):
    print(name +' Slowest Common Denominator '+ tail)    
sld('Brent is the', 'in the World' )
#We passed two arguments and wrapped them around the string in the function.
>>Brent is the Slowest Common Denominator in the World

Python Tutorial: Python List Examples

Lets get a bit more flexible, lets pass a list. We will pass variable length arguments meaning, you can pass as many lists as you want. Quick refresher on lists, a list holds a number of objects inside of a sequence. A tuple is similar but the difference is a tuple cannot be modified while a list can. Example of a list.

#!/user/bin/python
BadSocialMedia = ['Facebook', 'MySpace']
#Print the List
print(BadSocialMedia)
#Print just one object in the list
print(BadSocialMedia[0])
#Remember counts start at 0 in Python
print(BadSocialMedia[1])
#Replace an Object in the 2nd place [1]. Note: Lists are mutable eg. we can change values.
BadSocialMedia[1] = 'Pinterest'
print(BadSocialMedia)
#Create or append a new value in slot [2] the 3rd slot
BadSocialMedia.append('Twitter')
print(BadSocialMedia)

The output would look like this:

['Facebook', 'MySpace']
Facebook
MySpace
['Facebook', 'Pinterest']
['Facebook', 'Pinterest', 'Twitter']

Python Tutorial: Example Passing Variable Length Argument to a List in a Function

Now lets pass a list to a function notice I am using the built-in ‘str’ function to convert the list to a string in order to print the whole thing in the function.

#!/user/bin/python
def socfun(args):
    print('Here is the whole list passed ' +str(args))
    print('Here is just one value parsed w/str ' +str(args[0])) 
    print('Here is just one value parsed w/o str ' + args[0]) 
#Define the List  
BadSocialMedia = ['Facebook', 'MySpace', 'Pinterest']
#Call the function passing the List
socfun(BadSocialMedia)

Output:

Here is the whole list passed ['Facebook', 'MySpace', 'Pinterest']
Here is just one value parsed w/str Facebook
Here is just one value parsed w/out str Facebook

Python Tutorial: Python Dictionaries

A Dictionary is like it sounds. It can take a keyword and associate it to a value or object. This is often referred to as an Associative Array. Since most reading this would be interested in infrastrcuture and/or networks a good example would be a mac address table entry. A BCAM (Binary Content Addressable Memory) lookup or search index would be an associative array. If we had two fields one being a port and the other being the MAC address learned on that port are associated with a dictionary entry could look like this:

Gig2/10 --> 1cdf.0f95.08ba
Gig4/22 --> 000c.2997.23dd

In Python that would look like this:

#!/user/bin/python
macAddrTable = {'Gig2/10':'1cdf.0f95.08ba', 'Gig4/22':'000c.2997.23dd'}
print(macAddrTable)
print('Who is on port gig2/10? ' + macAddrTable['Gig2/10'])
Output:
{'Gig4/22': '000c.2997.23dd', 'Gig2/10': '1cdf.0f95.08ba'}
Who is on port gig2/10? 1cdf.0f95.08ba

Python Tutorial: Python Dictionaries and Functions
  • Let’s add a few functions. One will be a new MAC address was flooded on port Gigabit 3/2. We will pass the current state of the MAC addr tables and update it with the new entry on Gig3/2.
  • The next function will replace a MAC an existing association on Gig4/22 with the new one heard from flooding.
#!/user/bin/python
def macAdd(macAddrTable):
    #new MAC address was learned on port Gig3/2 Update the tables
    print('We heard a new MAC address flood, lets update the MAC tables')
    macAddrTable['Gig3/2'] = 'd067.e5e5.1354'
    print(macAddrTable)
    print()

def macUpdate(macAddrTable):
    #A new MAC address was learned on port Gig3/2 Update the tables
    print('We heard a defferent MAC address flood on 4/22, lets replace the MAC entry')
    macAddrTable['Gig4/22'] = '0004.009d.039e'
    print(macAddrTable)

macAddrTable = {'Gig2/10':'1cdf.0f95.08ba',
                'Gig4/22':'000c.2997.23dd'}

print('The original MAC address table is:')
print(macAddrTable)
print()
print('Who is on port gig2/10 ??? --> ' + macAddrTable['Gig2/10'])
print()
#Call the macAdd function and pass the current state of the tables
macAdd(macAddrTable)
#Call the macUpdate function and pass the current state of the tables
macUpdate(macAddrTable)

The output looks like this:

The original MAC address table is:
{'Gig4/22': '000c.2997.23dd', 'Gig2/10': '1cdf.0f95.08ba'}

Who is on port gig2/10 ??? --> 1cdf.0f95.08ba

We heard a new MAC address flood, lets update the MAC tables
{'Gig4/22': '000c.2997.23dd', 'Gig2/10': '1cdf.0f95.08ba', 'Gig3/2': 'd067.e5e5.1354'}

We heard a defferent MAC address flood on 4/22, lets replace the MAC entry
{'Gig4/22': '0004.009d.039e', 'Gig2/10': '1cdf.0f95.08ba', 'Gig3/2': 'd067.e5e5.1354'}

Going to wrap up there for this review of Lists, Dictionaries and how they interact with Functions. We will get into some Object Oriented Programming (OOP) in the next post.



Thanks for stopping by.


About the Author

Brent SalisburyBrent Salisbury works as a Network Architect, CCIE #11972. He blogs at NetworkStatic.net with a focus on disruptive technologies, that have a focus on operational efficiencies. Brent can be reached on Twitter @NetworkStatic.View all posts by Brent Salisbury →

  1. Ciprian TomoiagaCiprian Tomoiaga02-23-2013


    Again, a very nice and neat tutorial! I like them for their simplicity.
    Could I still make a small suggestion? It’s “OOP”, not “OOB” (like you said, from “Object Oriented Programming”)

  2. Brent SalisburyBrent Salisbury02-25-2013


    Hi Ciprian, Thanks for the nice comments and pointing out the typo, I was finishing a data center design and had “out of band” (OOB) on the brain lol.

    Respect,
    -Brent

  3. Saravana KumarSaravana Kumar03-13-2014


    Awesome, this is very clear for beginners like me. Thanks a lot Mr. Brent