Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
← Power Query for Data Analysis · Lesson 7 of 17

Module Six

📖 Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
7
Module 6 · Certified Power Query for Data Analysis Expert

📘 Module Six: Advanced M – Lists, Records, and Custom Functions

Welcome, young data champion! In Module Five, we learned the basics of M language – variables, steps, and simple functions. Now it is time to level up. In this module, we will explore lists (like bags of items), records (like cards with details), and custom functions (like recipes you invent yourself). You will learn how to loop through data, transform lists, and build your own powerful tools. By the end, you will be able to write M code that can handle almost any data challenge!

🎯 Learning Objectives

  • Understand lists and how to work with them in M.
  • Understand records and how to access their fields.
  • Create and use custom functions that accept parameters.
  • Use List.Transform to apply a function to every item in a list.
  • Use Record.Combine and Record.Field to work with records.
  • Combine lists and records with tables.
  • Handle errors gracefully using try and otherwise.
  • Write reusable M code that saves time.

📖 Warm‑up Story: The Magic Toolbox

Fatima loves fixing things. Her grandfather gives her a toolbox with many compartments. One compartment holds screws (like a list of values). Another holds instruction cards (like records with details). She also has a special tool that can turn any screw and any card into a new creation – that’s like a custom function!
In this module, you will build your own toolbox. You will learn to store data in lists, organize it in records, and create functions that can work on any data you give them. Let’s start building!

📚 Main Lessons

Lesson 1: What is a List in M?

Definition: A list is a collection of values enclosed in curly braces { }.

Why important: Lists let you store many items together and work with them all at once.

Simple explanation: Like a bag of marbles – you can count them, add more, or take some out.

Real‑life example: A shopping list: {"milk", "bread", "eggs"}.

School example: A list of test scores: {80, 90, 70}.

Home example: A list of chores: {"sweep", "wash", "cook"}.

Nigerian example: A list of states: {"Lagos", "Abuja", "Kano"}.

let
    MyList = {10, 20, 30, 40}
in
    MyList

Mini summary: A list is a collection of items inside { }.

Lesson 2: Accessing Items in a List

Definition: You can get an item from a list using its position (index), starting from 0.

Why important: You often need to pick one specific item from a list.

Simple explanation: Like picking the third marble from your bag.

Real‑life example: The first item on a list is position 0.

School example: In a list of scores, {80,90,70}, the second score is at index 1 (90).

Home example: Your chore list – index 0 is “sweep”.

Nigerian example: List of states – index 0 is “Lagos”.

let
    MyList = {10, 20, 30},
    FirstItem = MyList{0}   // 10
in
    FirstItem

Mini summary: Use {index} to pick an item from a list.

Lesson 3: List.Transform – Changing Every Item

Definition: List.Transform applies a function to each item in a list and returns a new list.

Why important: It lets you change all items at once – like doubling every number.

Simple explanation: Like giving every marble a coat of paint – all at once.

Real‑life example: Convert all prices from naira to dollars.

School example: Add 5 marks to every score.

Home example: Double the quantity of each item in a recipe.

Nigerian example: Add VAT (7.5%) to every price.

let
    MyList = {10, 20, 30},
    NewList = List.Transform(MyList, each _ * 2)   // {20, 40, 60}
in
    NewList

Mini summary: List.Transform changes every item in a list.

Lesson 4: What is a Record in M?

Definition: A record is a set of fields with names and values, like a row in a table.

Why important: Records organize data with labels, so you know what each value means.

Simple explanation: Like a student ID card – it has Name, Age, and Class.

Real‑life example: A product record: [Product="Milk", Price=200].

School example: A student record: [Name="Ade", Score=80].

Home example: A chore record: [Chore="Sweep", Time="10am"].

Nigerian example: A state record: [State="Lagos", Population=20M].

let
    MyRecord = [Name="Ade", Age=10, Class="P5"]
in
    MyRecord

Mini summary: A record is a labelled collection of values inside [ ].

Lesson 5: Accessing Fields in a Record

Definition: You can get a field’s value using the dot notation or Record.Field.

Why important: You need to extract specific information from a record.

Simple explanation: Like looking at the “Name” on an ID card.

Real‑life example: Get the price from a product record.

School example: Get the score from a student record.

Home example: Get the time from a chore record.

Nigerian example: Get the population from a state record.

let
    MyRecord = [Name="Ade", Score=80],
    StudentName = MyRecord[Name]   // or MyRecord.Name
in
    StudentName

Mini summary: Use [FieldName] to get a value from a record.

Lesson 6: Combining Records – Record.Combine

Definition: Record.Combine merges two or more records into one.

Why important: You may have information in separate records that you want to bring together.

Simple explanation: Like sticking two cards together to make a bigger card.

Real‑life example: Combine product details and price records.

School example: Combine student name and marks records.

Home example: Combine chore name and time records.

Nigerian example: Combine state name and capital records.

let
    Rec1 = [Name="Ade", Age=10],
    Rec2 = [Score=80, Class="P5"],
    Combined = Record.Combine({Rec1, Rec2})
in
    Combined   // [Name="Ade", Age=10, Score=80, Class="P5"]

Mini summary: Record.Combine merges records.

Lesson 7: Lists of Records – Tables in Disguise

Definition: A list of records is like a table – each record is a row.

Why important: Many data sources give you a list of records.

Simple explanation: Like a class register – each row is a student record.

Real‑life example: A list of products, each with Name and Price.

School example: A list of students, each with Name and Score.

Home example: A list of chores, each with Chore and Time.

Nigerian example: A list of states, each with State and Capital.

let
    MyTable = {
        [Name="Ade", Score=80],
        [Name="Bola", Score=90],
        [Name="Chidi", Score=70]
    }
in
    MyTable

Mini summary: A list of records is a great way to store tabular data.

Lesson 8: Transforming a List of Records

Definition: You can use List.Transform on a list of records to change or extract fields.

Why important: It lets you manipulate each row of your data.

Simple explanation: Like going through each student and adding 5 marks.

School example: Add 10 to every score in a list.

Home example: Add a “Done” field to every chore.

Nigerian example: Add a “Region” field to every state record.

let
    Data = {
        [Name="Ade", Score=80],
        [Name="Bola", Score=90]
    },
    Updated = List.Transform(Data, each _ & [Score = [Score] + 5])
in
    Updated   // scores become 85 and 95

Mini summary: You can transform lists of records row by row.

Lesson 9: Custom Functions – Your Own Recipes

Definition: A custom function is a block of code you write to perform a specific task.

Why important: You can reuse the same code many times with different inputs.

Simple explanation: Like a recipe for “fried rice” – you can make it whenever you want.

Real‑life example: A function to calculate discount.

School example: A function to calculate average.

Home example: A function to convert currency.

Nigerian example: A function to add VAT.

let
    AddTen = (x) => x + 10,
    Result = AddTen(5)   // 15
in
    Result

Mini summary: Functions are reusable recipes in M.

Lesson 10: Functions with Multiple Parameters

Definition: A function can take more than one input, like (x, y) => x + y.

Why important: Many tasks need more than one piece of information.

Simple explanation: Like adding two numbers – you need both numbers.

School example: A function to calculate total (maths + english).

Home example: A function to calculate total cost (price * quantity).

Nigerian example: A function to calculate total with VAT.

let
    Add = (x, y) => x + y,
    Sum = Add(5, 3)   // 8
in
    Sum

Mini summary: Functions can have many inputs.

Lesson 11: Using Functions with Lists – List.Transform and Custom Functions

Definition: You can pass a custom function to List.Transform to apply it to every item.

Why important: It gives you complete flexibility.

Simple explanation: Like having a special machine that can do any job you tell it.

School example: Apply a “pass/fail” function to every score.

Home example: Apply a “discount” function to every price.

Nigerian example: Apply a “region” function to every state.

let
    AddTen = (x) => x + 10,
    MyList = {10, 20, 30},
    NewList = List.Transform(MyList, AddTen)   // {20, 30, 40}
in
    NewList

Mini summary: Custom functions make List.Transform very powerful.

Lesson 12: Error Handling with try and otherwise

Definition: “try” attempts a step; if it fails, “otherwise” gives a fallback value.

Why important: It prevents your code from crashing when something goes wrong.

Simple explanation: Like wearing a helmet – if you fall, it protects you.

School example: If a score is missing, use 0.

Home example: If an item has no price, set it to 100.

Nigerian example: If a state population is missing, use “Unknown”.

let
    SafeDivide = (a, b) => try a / b otherwise 0,
    Result = SafeDivide(10, 0)   // 0 (no error)
in
    Result

Mini summary: try…otherwise keeps your code safe from errors.

Lesson 13: Building a Complete Custom Function

Definition: A full function can have multiple steps inside using let…in.

Why important: Complex tasks need multiple steps.

Simple explanation: Like a recipe with many steps – mix, knead, bake.

School example: A function to calculate grade (A, B, C) from score.

Home example: A function to calculate total with tax and discount.

Nigerian example: A function to clean a name (capitalize, remove spaces).

let
    Grade = (score) =>
        let
            GradeText = if score >= 70 then "A" else "B"
        in
            GradeText,
    Result = Grade(85)   // "A"
in
    Result

Mini summary: Functions can have multiple steps inside.

Lesson 14: Using Record.Field and Record.HasField

Definition: Record.Field gets a field value; Record.HasField checks if a field exists.

Why important: Sometimes you don’t know if a field is present.

Simple explanation: Like checking if a student has a “Score” field before using it.

School example: Only add marks if the “Score” field exists.

Home example: Only add a price if the “Price” field exists.

Nigerian example: Only add a capital if the “Capital” field exists.

let
    MyRecord = [Name="Ade"],
    HasScore = Record.HasField(MyRecord, "Score")   // false
in
    HasScore

Mini summary: Record.Field and HasField help you work safely with records.

Lesson 15: Recursion – Functions Calling Themselves

Definition: Recursion is when a function calls itself to solve a problem.

Why important: It is useful for repetitive tasks like summing a list.

Simple explanation: Like counting marbles one by one until you reach the end.

School example: Sum all numbers in a list.

Home example: Count all items in a shopping list.

Nigerian example: Count all states in a list.

let
    SumList = (lst) =>
        if List.Count(lst) = 0 then 0
        else List.First(lst) + SumList(List.Skip(lst, 1)),
    Result = SumList({10, 20, 30})   // 60
in
    Result

Mini summary: Recursion is a function that calls itself – powerful but advanced.

🔑 Key Vocabulary (simple definitions)

  • List: A collection of values in { }.
  • Record: A set of labelled values in [ ].
  • Index: The position of an item in a list (starting from 0).
  • List.Transform: A function that changes every item in a list.
  • Record.Combine: Merges two records.
  • Custom function: A reusable block of code.
  • Parameter: An input to a function.
  • try … otherwise: Error handling that prevents crashes.
  • Recursion: A function that calls itself.
  • Field: A named part of a record.

🧠 Important Concepts

  • Immutability: Lists and records are not changed; new ones are created.
  • Function composition: You can pass functions to other functions.
  • Scope: Variables inside a function are not visible outside.
  • Lazy evaluation: M only computes values when needed.

📝 Step‑by‑Step Explanations

How to create a custom function that cleans a name

  1. Write: CleanName = (fullName) => Text.Proper(Text.Trim(fullName))
  2. Test it: CleanName(" ade ojo ") returns “Ade Ojo”.
  3. Use it in List.Transform to clean many names.

How to safely access a record field

  1. Use Record.HasField(record, "FieldName") to check.
  2. If true, use Record.Field(record, "FieldName").
  3. If false, provide a default value.

🌍 Real‑life Examples

  • E-commerce: Use List.Transform to calculate discounts on a list of products.
  • Healthcare: Use records to store patient data and functions to calculate BMI.
  • Finance: Use custom functions to calculate interest rates.

🇳🇬 Nigerian Examples

  • Nigerian Stock Exchange: Use lists to track share prices and functions to calculate returns.
  • Population data: Use records for each state and functions to compute density.
  • School system: Use List.Transform to add scores for all students.

🧸 Fun Examples

  • A list of your favourite games – transform to add “(fun)” to each.
  • A record for your pet – get its age field.
  • A custom function that doubles your allowance – use it every week.

🏠 Everyday Examples

  • List of homework tasks – transform to add “due date”.
  • Record of a recipe – get cooking time field.
  • Custom function to convert miles to kilometres.

👩‍🏫 Teacher Notes

  • Emphasize the difference between lists (ordered) and records (labelled).
  • Use real data to demonstrate List.Transform and Record.Combine.
  • Encourage students to write simple functions and test them.

👨‍👩‍👧 Parent Tips

  • Help your child create a list of family members and transform it.
  • Show them how to make a record for each family member.
  • Practice writing simple functions together.

💡 Interesting Facts

  • Lists in M can hold any type of value – numbers, text, even other lists!
  • Records are used extensively in Power Query to pass parameters.
  • Many built‑in Power Query functions are written in M.

🤔 Did You Know?

  • You can convert a list of records directly to a table using Table.FromRecords.
  • M supports infinite lists using functions like List.Generate.

🧷 Remember This

  • Lists are for collections; records are for labelled data.
  • Use List.Transform to change all items in a list.
  • Custom functions make your code reusable and clean.
  • Always handle errors with try…otherwise.

⚠️ Common Mistakes

  • Using { } for records and [ ] for lists – they are opposite!
  • Forgetting that list indices start at 0.
  • Not checking if a field exists before accessing it.
  • Writing functions that are too complex – break them down.

✅ Best Practices

  • Always give your lists and records meaningful names.
  • Write small, focused functions that do one thing well.
  • Use comments to explain complex logic.
  • Test your functions with simple inputs first.

🖼️ Illustrations

List as a Bag of Marbles
+-----+-----+-----+-----+
| 10  | 20  | 30  | 40  |
+-----+-----+-----+-----+
Index: 0    1    2    3
Record as an ID Card
+------------------+
| Name: Ade        |
| Age:  10         |
| Class: P5        |
+------------------+
List of Records (Table)
+----------+----------+----------+
| Name     | Score    | Grade    |
+----------+----------+----------+
| Ade      | 80       | A        |
+----------+----------+----------+
| Bola     | 90       | A        |
+----------+----------+----------+

📊 Comparison Tables

ConceptSyntaxUse
List{1,2,3}Collection of values
Record[Name="Ade"]Labelled values
List.TransformList.Transform(list, each _ * 2)Change every item
Record.CombineRecord.Combine({rec1, rec2})Merge records

📌 End‑of‑Module Summary

You have now mastered lists, records, and custom functions in M! You can create lists of any type, access items by index, and transform entire lists with List.Transform. You know how to build records, combine them, and work with lists of records. You have written your own functions with parameters and even used error handling to make your code safe. You are now equipped to write powerful, reusable M code that can handle complex data challenges. Well done!

❓ Frequently Asked Questions

  1. What is the difference between a list and a record? – A list is a collection of values; a record has labelled fields.
  2. How do I access the first item in a list? – Use MyList{0}.
  3. How do I merge two records? – Use Record.Combine({rec1, rec2}).
  4. What does List.Transform do? – It applies a function to every item and returns a new list.
  5. How do I write a custom function? – Use (parameters) => expression or let…in.
  6. What is try … otherwise? – It attempts an operation and gives a default if it fails.
  7. Can a function have multiple steps? – Yes, use let…in inside the function.
  8. What is recursion? – A function that calls itself.
  9. How do I check if a field exists in a record? – Use Record.HasField.
  10. Can I convert a list of records to a table? – Yes, use Table.FromRecords.

📝 Review Questions

  1. What is a list in M?
  2. How do you access the third item in a list?
  3. What does List.Transform do?
  4. What is a record?
  5. How do you get a field from a record?
  6. What is Record.Combine used for?
  7. How do you create a custom function?
  8. What is the purpose of try … otherwise?
  9. What is a parameter in a function?
  10. How do you apply a custom function to every item in a list?
  11. What is recursion?
  12. How do you check if a field exists in a record?
  13. What does Table.FromRecords do?
  14. Give an example of a list of records.
  15. Why is error handling important?

✍️ Fill‑in‑the‑Blank

  1. A list is enclosed in _______ braces.
  2. A record is enclosed in _______ brackets.
  3. List.Transform applies a function to every _______ in a list.
  4. _______ combines two or more records.
  5. A _______ is a block of code that you can reuse.

✅ True or False

  1. List indices start at 1. (False – start at 0)
  2. A record can have only one field. (False – can have many)
  3. List.Transform changes the original list. (False – it creates a new list)
  4. try … otherwise prevents errors. (True)
  5. Recursion is a function that calls itself. (True)

🔘 Multiple Choice Questions

  1. Which syntax creates a list?
    a) [1,2,3] b) {1,2,3} c) (1,2,3) d) <1,2,3>
    Answer: b
  2. Which syntax creates a record?
    a) [Name="Ade"] b) {Name="Ade"} c) (Name="Ade") d)
    Answer: a
  3. How do you get the second item of a list MyList?
    a) MyList{1} b) MyList[1] c) MyList(1) d) MyList.1
    Answer: a
  4. What does List.Transform do?
    a) Transforms a record b) Transforms a list c) Combines lists d) Filters a list
    Answer: b
  5. Which function merges records?
    a) List.Combine b) Record.Combine c) Table.Combine d) Combine.Records
    Answer: b
  6. What is the correct way to write a function that doubles a number?
    a) (x) => x * 2 b) x => x * 2 c) (x) => x + 2 d) x => x + 2
    Answer: a
  7. What does try … otherwise do?
    a) Tries a step, otherwise gives a default b) Tries a step, otherwise stops c) Combines steps d) Deletes steps
    Answer: a
  8. What is recursion?
    a) A function that calls itself b) A function that calls another c) A list of functions d) A record of functions
    Answer: a
  9. How do you check if a record has a field?
    a) Record.HasField b) Record.FieldExists c) Record.Contains d) Record.Has
    Answer: a
  10. Which function converts a list of records to a table?
    a) Table.FromRecords b) Table.FromList c) Table.Convert d) Table.Records
    Answer: a
  11. What is an index?
    a) The position of an item in a list b) A type of record c) A function d) An error
    Answer: a
  12. Can a list hold different data types?
    a) Yes b) No c) Only numbers d) Only text
    Answer: a
  13. What is the purpose of a custom function?
    a) Reuse code b) Create errors c) Delete data d) Format text
    Answer: a
  14. What does List.Transform return?
    a) A new list b) The original list c) A record d) A table
    Answer: a
  15. Which is a best practice?
    a) Use meaningful names b) Use short names c) No comments d) No functions
    Answer: a

🔗 Matching Exercises

Match the M concept with its description:

ConceptDescription
1. ListA. A collection of values in { }
2. RecordB. A set of labelled fields in [ ]
3. List.TransformC. Applies a function to every item
4. try … otherwiseD. Error handling

Answers: 1-A, 2-B, 3-C, 4-D

✏️ Short Answer Questions

  1. Explain the difference between a list and a record.
  2. Write an M expression to create a list of numbers from 1 to 5.
  3. How do you apply a function that adds 10 to every number in a list?
  4. Write a custom function that takes a score and returns “Pass” if score ≥ 50.
  5. Why would you use try … otherwise?

📖 Scenario‑based Exercises

Scenario 1: You have a list of product records: [Product="Rice", Price=1000], etc. Write M code to add a 10% tax to each product’s price.

Scenario 2: You have a record with Name, Age, and Score. Write a function that returns the grade based on the score.

👥 Group Activity

Each group creates a list of 10 records (e.g., students with Name, Score). Then, using List.Transform and a custom function, they transform the list to add a “Grade” column. Groups compare their approaches.

🧑‍🎓 Individual Activity

Write a custom function that cleans a list of names (capitalizes each, removes extra spaces). Test it on a list of your friends’ names.

🗣️ Classroom Discussion Questions

  1. When would you use a list instead of a record?
  2. Why is immutability important in M?
  3. How can custom functions save you time?

🛠️ Mini Project

Build a Power Query that takes a list of state records (Name, Capital, Population). Use a custom function to add a “Region” column (e.g., South, North) based on the state. Output the transformed list.

💻 Practical Assignment

Using a sample dataset of employees (Name, Department, Salary), write M code to: (1) Create a list of records, (2) Add a “Bonus” column (10% of salary), (3) Filter to only employees with salary > 50000. Submit your M code.

🏆 Challenge Exercise

Write a recursive function that sums all numbers in a list without using List.Sum. Test it with a list of 10 numbers.

🔍 Quiz Answers

Fill‑in‑the‑Blank: 1. curly 2. square 3. item 4. Record.Combine 5. function

True or False: 1-F, 2-F, 3-F, 4-T, 5-T

Multiple Choice: 1-b, 2-a, 3-a, 4-b, 5-b, 6-a, 7-a, 8-a, 9-a, 10-a, 11-a, 12-a, 13-a, 14-a, 15-a

🎁 Key Takeaways

  • Lists store ordered collections; records store labelled data.
  • List.Transform is a powerful way to change all items in a list.
  • Custom functions let you reuse code and keep your work clean.
  • Error handling with try…otherwise makes your code robust.
  • Practice with lists, records, and functions – they are the building blocks of M.

🔜 Preparation for Module Seven

In Module Seven, we will dive into “Performance and Efficiency in Power Query”. You will learn how to make your queries run faster, reduce memory usage, and handle big data like a pro. Get ready to optimize your data magic!

Note: This is Module Six. Module Five covered basic M. We now move to Module Seven, where we will focus on making our queries efficient and fast. Keep coding – you are becoming a true M master!

🏆 Get Certified

🔒

Earn this certificate

Every lesson is already free to read. Sign up, finish the lessons, pass the exam (₦2,000 or 20,000 coins), and get a verified certificate with your name on it.

🎓 Sign Up to Get Certified
🛠️ Practice Tools
Hands-on simulators & labs - subscription required.
→
🎯 Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
→