Python for Machine Learning (7-day mini-course)

Python for Machine Learning Crash Course.
Learn core Python in 7 days.

Python is an amazing programming language. Not only it is widely used in machine learning projects, you can also find its presence in system tools, web projects, and many others. Having good Python skills can make you work more efficiently because it is famous for its simplicity. You can try out your idea faster. You can also present your idea in a concise code in Python.

As a practitioner, you are not required to know how the language is built, but you should know that the language can help you in various tasks. You can see how concise a Python code can be, and how much the functions from its libraries can do.

In this crash course, you will discover some common Python techniques, from doing the exercises in seven days.

This is a big and important post. You might want to bookmark it.

Let’s get started.

Python for Machine Learning (7-Day Mini-Course)

Python for Machine Learning (7-Day Mini-Course)
Photo by David Clode, some rights reserved.

Who Is This Crash-Course For?

Before you get started, let’s make sure you are in the right place.

This course is for developers who may know some programming. Maybe you know another language, or you may be able to write a few lines of code in Python to do something simple.

The lessons in this course do assume a few things about you, such as:

  • You know your way around basic Python.
  • You understand the basic programming concepts, such as variables, arrays, loops, and functions.
  • You can work with Python in command line or inside an IDE.

You do NOT need to be:

  • A star programmer
  • A Python expert

This crash course can help you transform from a novice programmer to an expert who can code comfortably in Python.

This crash course assumes you have a working Python 3.7 environment installed. If you need help with your environment, you can follow the step-by-step tutorial here:

Crash-Course Overview

This crash course is broken down into seven lessons.

You could complete one lesson per day (recommended) or complete all of the lessons in one day (hardcore). It really depends on the time you have available and your level of enthusiasm.

Below is a list of the seven lessons that will get you started and productive with Python:

  • Lesson 01: Manipulating lists
  • Lesson 02: Dictionaries
  • Lesson 03: Tuples
  • Lesson 04: Strings
  • Lesson 05: List comprehension
  • Lesson 06: Enumerate and zip
  • Lesson 07: Map, filter, and reduce

Each lesson could take you between 5 and up to 30 minutes. Take your time and complete the lessons at your own pace. Ask questions, and even post results in the comments online.

The lessons might expect you to go off and find out how to do things. This guide will give you hints, but part of the point of each lesson is to force you to learn where to go to look for help with and about the algorithms and the best-of-breed tools in Python.

Post your results in the comments; I’ll cheer you on!

Hang in there; don’t give up.

Lesson 01: Manipulating lists

In this lesson, you will discover a basic data structures in Python, the list.

In other programming languages, there are arrays. The counterpart in Python is list. A Python list does not limit the number of elements it stores. You can always append elements into it, and it will automatically expand its size. Python list also does not require its elements to be in the same type. You can mix and match different elements into a list.

In the following, we create a list of some integers, and then append a string into it:

Python lists are zero-indexed. Namely, to get the first element in the above list, we do:

This will print 1 to the screen.

Python lists allow negative indices to mean counting elements from the back. So the way to print the last element from the above list is:

Python also has a handy syntax to find a slice of a list. To print the last two elements, we do:

Usually, the slice syntax is start:end where the end is not included in the result. If omitted, the default will be the first element as the start and the one beyond the end of the entire list as the end. We can also use the slice syntax to make a step.” For example, this is how we can extract even and odd numbers:

Your Task

In the above example of getting odd numbers from a list of 1 to 10, you can make a step size of -2 to ask the list go backward. How can you use the slicing syntax to print [9,7,5,3,1]? How about [7,5,3]?

Post your answer in the comments below. I would love to see what you come up with.

In the next lesson, you will discover the Python dictionary.

Lesson 02: Dictionaries

In this lesson, you will learn Python’s way of storing a mapping.

Similar to Perl, an associative array is also a native data structure in Python. It is called a dictionary or dict. Python uses square brackets [] for list and uses curly brackets {} for dict. A Python dict is for key-value mapping, but the key must be hashable, such as a number or a string. Hence we can do the following:

Adding a key-value mapping to a dict is similar to indexing a list:

We can check if a key is in a dict using the \codetext{in} operator, for example:

But in Python dict, we can use the \codetext{get()} function to give us a default value if the key is not found:

But indeed, you are not required to provide a default to \codetext{get()}. If you omitted it, it will return \codetext{None}. For example:

It will produce

Since the Python dict is a key-value mapping, we can extract only the keys or only the values, using:

We used list() to convert the keys or values to a list for better printing.
%
The other way to manipulate a list is with the items() function. Its result would be key-value pairs:

This prints:

Since they are pairs in a list, we can use list manipulation syntax to combine items from two dicts and produce a combined dict. The following is an example:

This will print:

Your Task

Depending on your version of Python, the last example above can have a simplified syntax:

Check in your installation if you can reproduce the same result as the last example.

In the next lesson, you will discover the tuple as a read-only list.

Lesson 03: Tuples

In this lesson, you will learn the tuple as a read-only data structure.

Python has a list that behaves like an array of mixed data. A Python tuple is very much like a list, but it cannot be modified after it is created. It is immutable. Creating a tuple is just like creating a list, except using parentheses, ():

You can refer to the first element as x[0] just like the case of a list. But you cannot assign a new value to x[0] because a tuple is immutable. If you try to do it, Python will throw a TypeError with the reason that the tuple does not support the item assignment.

A tuple is handy to represent multiple return values of a function. For example, the following function produces a value’s multiple powers as a tuple:

This will print:

which is a tuple. But we usually use the unpacking syntax:

In fact, this is a powerful syntax in Python in which we can assign multiple variables in one line. For example,

This will assign variable count to integer 0 and variable elements to an empty list. Because of the unpacking syntax, this is the Pythonic way of swapping the value of two variables:

Your Task

Consider a list of tuples:

You can sort this list using sorted(x). What is the result? From the result of comparing tuples, how does Python understand which tuple is less than or greater than another? Which is greater, the tuple ("alpha", 0.5) or the tuple ("alpha", 0.5, 1)?

Post your answer in the comments below. I would love to see what you come up with.

In the next lesson, you will learn about Python strings.

Lesson 04: Strings

In this lesson, you will learn about creating and using strings in Python.

A string is the basic way of storing text in Python. All Python strings are unicode strings, meaning you can put unicode into it. For example:

The smiley is a unicode character of code point 0x1F600. Python string comes with a lot of functions. For example, we can check if a string begins or ends with a substring using:

Then to check whether a string contains a substring, use the “in” operator:

There is a lot more. Such as split() to split a string, or upper() to convert the entire string into uppercase.

One special property of Python strings is the implicit concatenation. All of the following produce the string "hello world":

The rule is, Python will normally use \ as a line continuation. But if Python sees two strings placed together without anything separating them, the strings will be concatenated. Hence the first example above is to concatenate "hel" with "lo world". Likewise, the last example concatenated two strings because they are placed inside parentheses.

A Python string can also be created using a template. It is often seen in print() functions. For example, below all produce "hello world" for variable y:

Your Task

Try to run this code:

This is to fill a template using a dictionary. The first uses the %-syntax while the second uses format syntax. Can you modify the code above to print only 2 decimal places? Hints: Check out https://docs.python.org/3/library/string.html!

Post your answer in the comments below. I would love to see what you come up with.

In the next lesson, you will discover list comprehension syntax in Python.

Lesson 05: List Comprehension

In this lesson, you will see how list comprehension syntax can build a list on the fly.

The famous fizz-buzz problem prints 1 to 100 with all 3-multiples replaced with “fizz,” all 5-multiples replaced with “buzz,” and if a number is both a multiple of 3 and 5, print “fizzbuzz.” You can make a for loop and some if statements to do this. But we can also do it in one line:

We set up the list numbers using list comprehension syntax. The syntax looks like a list but with a for inside. Before the keyword for, we define how each element in the list will be created.

List comprehension can be more complicated. For example, this is how to produce all multiples of 3 from 1 to 100:

And this is how we can print a $10\times 10$ multiplication table:

And this is how we can combine strings:

This prints:

Your Task

Python also has a dictionary comprehension. The syntax is:

Now try to create a dictionary mapping using dictionary comprehension that maps a string x to its length len(x) for these strings:

Post your answer in the comments below. I would love to see what you come up with.

In the next lesson, you will discover two very useful Python functions: enumerate() and zip().

Lesson 06: Enumerate and Zip

In this lesson, you will learn an the enumerate() function and zip() function.

Very often, you will see you’re writing a for-loop like this:

But here we need the loop variable n just to use as an index to access the list x. In this case, we can ask Python to index the list while doing the loop, using enumerate():

The result of enumerate() produces a tuple of the counter (default starts with zero) and the element of the list. We use the unpacking syntax to set it to two variables.

If we use the for-loop like this:

Python has a function zip() to help:

The zip() function is like a zipper, taking one element from each input list and putting them side by side. You may provide more than two lists to zip(). It will produce all matching items (i.e., stop whenever it hits the end of the shortest input list).

Your task

Very common in Python programs, we may do this:

Then, we can get the list of 1 to 10, the square of them, and the cube of them using zip() (note the * before results in the argument):

Try this out. Can you recombine numbers, squares, and cubes back to results? Hints: Just use zip().

In the next lesson, you will discover three more Python functions: map(), filter(), and reduce().

Lesson 07: Map, Filter, and Reduce

In this lesson, you will learn the Python functions map(), filter(), and reduce().

The name of these three functions came from the functional programming paradigm. In simple terms, map() is to transform elements of a list using some function, and filter() is to short list the elements based on certain criteria. If you learned list comprehension, they are just another method of list comprehension.

Let’s consider an example we saw previously:

Here we have a function defined, and map() uses the function as the first argument and a list as the second argument. It will take each element from a list and transform it using the provided function.

Using filter() is likewise:

If that’s appropriate, you can pass the return value from map() to filter() or vice versa.

You may consider map() and filter() as another way to write list comprehension (sometimes easier to read as the logic is modularized). The reduce() function is not replaceable by list comprehension. It scans the elements from a list and combines them using a function.

While Python has a max() function built-in, we can use reduce() for the same purpose. Note that reduce() is a function from the module functools:

By default, reduce() will give the first two elements to the provided function, then the result will be passed to the function again with the third element, and so on until the input list is exhausted. But there is another way to invoke reduce():

This result is the same, but the first call to the function uses the default value (-float("inf") in this case, which is negative infinity) and the first element of the list. Then uses the result and the second element from the list, and so on. Providing a default value is appropriate in some cases, such as the exercise below.

Your Task

Let’s consider a way to convert a bitmap to an integer. If a list [6,2,0,3] is provided, we should consider the list as which bit to assert, and the result should be in binary, 1001101, or in decimal, 77. In this case, bit 0 is defined to be the least significant bit or the right most bit.

We can use reduce to do this and print 77:

What should be the ??? above? Why?

Post your answer in the comments below. I would love to see what you come up with.

This was the final lesson.

The End!
(Look How Far You Have Come)

You made it. Well done!

Take a moment and look back at how far you have come.

You discovered:

  • Python list and the slicing syntax
  • Python dictionary, how to use it, and how to combine two dictionaries
  • Tuples, the unpacking syntax, and how to use it to swap variables
  • Strings, including many ways to create a new string from a template
  • List comprehension
  • The use of functions enumerate() and zip()
  • How to use map(), filter(), and reduce()

Summary

How did you do with the mini-course?
Did you enjoy this crash course?

Do you have any questions? Were there any sticking points?
Let me know. Leave a comment below.

Get a Handle on Python for Machine Learning!

Python For Machine Learning

Be More Confident to Code in Python

...from learning the practical Python tricks

Discover how in my new Ebook:
Python for Machine Learning

It provides self-study tutorials with hundreds of working code to equip you with skills including:
debugging, profiling, duck typing, decorators, deployment, and much more...

Showing You the Python Toolbox at a High Level for
Your Projects


See What's Inside

46 Responses to Python for Machine Learning (7-day mini-course)

  1. Avatar
    Mike Aronson June 4, 2022 at 1:40 am #

    >>> print(x[8::-2])
    [9, 7, 5, 3, 1]
    >>> print(x[6:0:-2])
    [7, 5, 3]

    • Avatar
      James Carmichael June 4, 2022 at 10:16 am #

      Keep up the great work Mike!

  2. Avatar
    Rishabh June 4, 2022 at 8:14 pm #

    for [9,7,5,3,1]
    x[-2::-2]

    for [7,5,3,1]
    x[-4::-2]

    • Avatar
      James Carmichael June 5, 2022 at 10:22 am #

      Thank you for the feedback Rishabh!

  3. Avatar
    Clara June 5, 2022 at 3:28 pm #

    Dear James,

    for [9,7,5,3,1] :

    print(x[8::-2]) or print(x[-2::-2])

    and for [7,5,3] :

    print(x[-4:-10:-2]) or print(x[-4:0:-2]) or print(x[6:0:-2]) or print(x[6:-10:-2])

    Thanks a lot.

    • Avatar
      James Carmichael June 6, 2022 at 8:58 am #

      You are very welcome Clara!

  4. Avatar
    Landon June 5, 2022 at 11:28 pm #

    [9,7,5,3,1] =========> print(x[-2:-11:-2])

    [7,5,3,1] ==========> print(x[-4:-10:-2])

  5. Avatar
    Balaji Doraibabu June 6, 2022 at 1:56 am #

    x = [(“alpha”,0.5),(“gamma”,0.1),(“beta”,1.1),(“alpha”,-3)]
    sorted(x)
    [(‘alpha’, -3), (‘alpha’, 0.5), (‘beta’, 1.1), (‘gamma’, 0.1)]

    Python sorts each tuple in the list by the respective position either alphabetically (a,b,c,d,….) or numerically (negative, zero, positive) first. If there are two tuples of the same value in that position, it will move on to compare the next item position for those tuples before it sorts to the next item of higher value in the same position.

    Tuple (‘alpha’, 0.5) is smaller than (‘alpha’, 0.5, 1)

    • Avatar
      James Carmichael June 6, 2022 at 9:01 am #

      Thank you for the feedback Balaji! Keep up the great work!

  6. Avatar
    Alberto June 7, 2022 at 8:43 pm #

    I totally agree with Balaji.

    Thank you guys for this course.

    Regards,

    • Avatar
      James Carmichael June 8, 2022 at 4:03 am #

      You are very welcome Alberto!

  7. Avatar
    Nanda Kishore June 9, 2022 at 3:23 am #

    x = [(“alpha”, 0.5), (“gamma”, 0.1), (“beta”, 1.1), (“alpha”, -3)]
    a = sorted(x)
    print(a)

    It prints : [(‘alpha’, -3), (‘alpha’, 0.5), (‘beta’, 1.1), (‘gamma’, 0.1)]

    x = [(“alpha”, 0.5), (“gamma”, 0.1), (“beta”, 1.1), (“alpha”, 0.5, 1)]
    a = sorted(x)
    print(a)

    It prints : [(‘alpha’, 0.5), (‘alpha’, 0.5, 1), (‘beta’, 1.1), (‘gamma’, 0.1)]

    • Avatar
      James Carmichael June 9, 2022 at 9:13 am #

      Keep up the great work Nanda!

      • Avatar
        Felix June 9, 2022 at 9:43 pm #

        A very nice primer for some list manipulation methods/functions that can make it more pleasurable (for me, at least) to read Python code. However, what do they have to do with machine learning, as the title suggests?

        While I’ve certainly used list comprehension, slicing, tuple unpacking, zip(), map(), filter(), etc. for data manipulation, munging, and cleaning, there was nothing about their use that specifically applied to machine learning. I might have used the resultant dataset for regression analysis, time-series analysis, or even for some non-data-science purpose.

        Could you perhaps provide some examples for each of the seven lessons that pertain to how you’ve used (or might use) them specifically for a machine learning purpose?

  8. Avatar
    Alberto June 9, 2022 at 8:06 pm #

    For two digits display:

    print(“latitude {lat:.2f}, longitude {lon:.2f}”.format(**coord))

  9. Avatar
    DV June 10, 2022 at 2:53 am #

    if “strawberry” in price:
    # if price is not found, assume $1
    print(“strawberry costs $1”)
    else:
    print(“strawberry costs $”, price[“strawberry”])

    Need to be “not in”

    • Avatar
      James Carmichael June 10, 2022 at 9:16 am #

      Thank you for the feedback DV!

  10. Avatar
    Jinho June 10, 2022 at 4:38 pm #

    for [7, 5, 3]

    back = x[6:1:-2]
    print (back)

  11. Avatar
    Alberto June 12, 2022 at 1:08 am #

    mapping = {key : len(key) for key in keys}

  12. Avatar
    Alberto June 12, 2022 at 1:32 am #

    results = []
    for n, s, c in zip(numbers, squares, cubes):
    results.append([n,s,c])

  13. Avatar
    Mehrdad Samadishadlou June 14, 2022 at 5:31 pm #

    LESSON 5:

    keys = [“one”, “two”, “three”, “four”, “five”, “six”, “seven”, “eight”, “nine”, “ten”]
    mapping = {key: len(key) for key in keys}
    print(mapping)

    • Avatar
      James Carmichael June 15, 2022 at 7:22 am #

      Thank you for the feedback!

  14. Avatar
    Yoohwany June 15, 2022 at 12:20 pm #

    Lesson 07
    bitmap = reduce(setbit, assertbits, 0)
    1: 0,6 return 64
    2: 64, 2 return 68
    3. 68, 0 return 69
    4. 69, 3 return 77

    • Avatar
      James Carmichael June 16, 2022 at 10:55 am #

      Thank you for the feedback Yoohwany!

  15. Avatar
    Ahmed Ali July 21, 2022 at 5:24 pm #

    rev = x[-2::-2]
    print(rev) # [9, 7, 5, 3, 1]

    limit = x[-4:1:-2]
    print(limit) # [7, 5, 3]

    • Avatar
      James Carmichael July 22, 2022 at 8:19 am #

      Keep up the great work Ahmed! Let us know if you have any questions we may assist you with.

  16. Avatar
    Ahmed Ali July 29, 2022 at 6:34 pm #

    Lesson 2:

    for me the statement: price = dict(pairs1 + pairs2) is not working for me
    I’m using v s code

  17. Avatar
    Ahmed Ali July 29, 2022 at 6:39 pm #

    Lesson 3:

    question 1
    after sorting

    [(‘alpha’, -3), (‘alpha’, 0.5), (‘beta’, 1.1), (‘gamma’, 0.1)]

    question 2
    after sorting
    [(‘alpha’, 0.5), (‘alpha’, 0.5, 1)]

    strings are sorted alphabetically

  18. Avatar
    Ahmed Ali July 31, 2022 at 8:33 am #

    lesson 5:

    keys = [“one”, “two”, “three”, “four”, “five”, “six”, “seven”, “eight”, “nine”, “ten”]
    mapping = {i: len(i) for i in keys}
    print(mapping)

  19. Avatar
    Ahmed Ali July 31, 2022 at 8:34 am #

    lesson 4:

    print(“latitude %(lat)0.2f, longitude %(lon)0.2f” % coord)

  20. Avatar
    Ahmed Ali August 6, 2022 at 6:03 pm #

    lesson 7
    ???=6, bitmap=79
    ???=2, bitmap=79
    ???=0, bitmap=77
    ???=3, bitmap=79

  21. Avatar
    Aminu September 4, 2022 at 5:40 am #

    num_list = [1,2,3,4,5,6,7,8,9,10]
    num_list2 = num_list[-4:0:-2]
    num_list2
    –> [7, 5, 3]

    • Avatar
      James Carmichael September 4, 2022 at 9:56 am #

      Thank you for the feedback Aminu!

  22. Avatar
    mahdi January 9, 2023 at 10:09 pm #

    x=[1,2,3,4,5,6,7,8,9,10]
    even=x[-1::-2]
    odd=x[-2::-2]
    f753=x[-4:0:-2]
    print(even)
    print(odd)
    print(f753)

    output:

    [10, 8, 6, 4, 2]
    [9, 7, 5, 3, 1]
    [7, 5, 3]

    • Avatar
      James Carmichael January 10, 2023 at 8:01 am #

      Thank you for your feedback mahdi!

  23. Avatar
    Tim Astras April 23, 2023 at 10:53 pm #

    Great Materiel, easy to follow along, colab is also working great as an environment. Thanks for all your help, time and making this content available.

    Tim

    • Avatar
      James Carmichael April 24, 2023 at 8:51 am #

      You are very welcome Tim! We appreciate your support!

  24. Avatar
    Scott May 10, 2023 at 3:12 am #

    Lesson 1

    For [9,7,5,3,1] : print(x[-2: : -2])
    For [7, 5,3] : print (x[-4: -9: -2])

  25. Avatar
    karthikeyan c August 27, 2023 at 1:07 am #

    lesson 6
    zip
    result =[]

    for n in range(1,11):
    squared,cubed = n**2, n**3
    result.append([n, squared, cubed])

    #print(result)

    number, squre, cubes = zip(*result)

    print(number)
    print(squre)
    print(cubes)

    op
    (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    (1, 4, 9, 16, 25, 36, 49, 64, 81, 100)
    (1, 8, 27, 64, 125, 216, 343, 512, 729, 1000)

  26. Avatar
    karthikeyan c August 27, 2023 at 1:32 am #

    for n in range(len(number)):
    print(“{} {} {}”.format(number[n],squre[n],cubes[n]))

    op
    1 1 1
    2 4 8
    3 9 27
    4 16 64
    5 25 125
    6 36 216
    7 49 343
    8 64 512
    9 81 729
    10 100 1000

  27. Avatar
    karthikeyan c August 27, 2023 at 1:46 am #

    lesson 6 zip

    for a, b, c in zip(number, squre, cubes ):
    print(“{} {} {}”.format(a, b, c))

    op:

    1 1 1
    2 4 8
    3 9 27
    4 16 64
    5 25 125
    6 36 216
    7 49 343
    8 64 512
    9 81 729
    10 100 1000

  28. Avatar
    Luke December 21, 2023 at 5:41 pm #

    >>> print(x[-2::-2])
    [9, 7, 5, 3, 1]

    >>> print(x[-4:-9:-2])
    [7, 5, 3]

    • Avatar
      James Carmichael December 22, 2023 at 10:35 am #

      Keep up the great work Luke! Let us know if you have any questions as you work through the course!

  29. Avatar
    Teh March 22, 2024 at 12:21 am #

    print(x[::-2])

    for [9, 7, 5, 3, 1]

    print(x[6:1:-2])

    for [7, 5, 3]

    • Avatar
      James Carmichael March 22, 2024 at 8:56 am #

      Hi Teh…Keep up the great work!

Leave a Reply