Variable-Length Arguments - 8.3.4 | 8. Advanced Python – Revision and Functions | CBSE Class 12th AI (Artificial Intelligence)
K12 Students

Academics

AI-Powered learning for Grades 8–12, aligned with major Indian and international curricula.

Professionals

Professional Courses

Industry-relevant training in Business, Technology, and Design to help professionals and graduates upskill for real-world careers.

Games

Interactive Games

Fun, engaging games to boost memory, math fluency, typing speed, and English skills—perfect for learners of all ages.

Interactive Audio Lesson

Listen to a student-teacher conversation explaining the topic in a relatable way.

Arbitrary Positional Arguments (*args)

Unlock Audio Lesson

0:00
Teacher
Teacher

Today, we’re exploring variable-length arguments, starting with `*args`. Can anyone tell me what they think `*args` means?

Student 1
Student 1

Does it mean we can pass different numbers of arguments to a function?

Teacher
Teacher

Exactly! When we define a function with `*args`, it collects all extra positional arguments into a tuple. For example, look at this function: `def total_marks(*marks): return sum(marks)`. How do you think it works?

Student 2
Student 2

It sums up any number of marks we provide, right? So can I pass in five or ten marks?

Teacher
Teacher

Exactly! You can pass any number of arguments, and the `sum()` function will handle it. Remember, we can think of `*args` as "A Variable Number of Arguments". Now, who can give me a summary of how to use it?

Student 3
Student 3

We define `*args` in the function definition, and then we can call the function with multiple values that will be summed up!

Teacher
Teacher

Good summary! And remember, your input is collected as a tuple.

Arbitrary Keyword Arguments (**kwargs)

Unlock Audio Lesson

0:00
Teacher
Teacher

Now let's shift gears to explore keyword arguments with `**kwargs`. Who can explain what happens when we use `**kwargs`?

Student 4
Student 4

Does it mean we can pass keyword arguments to the function, and it will collect them into a dictionary?

Teacher
Teacher

Absolutely! Look at this example: `def display_info(**kwargs): for key, value in kwargs.items(): print(f"{key} : {value}")`. What does it do?

Student 1
Student 1

It prints out each key-value pair that was passed to it, like `name` and `year`.

Teacher
Teacher

Correct! It allows us to easily pass attributes without needing to define every possible parameter. Remember: `**kwargs` stands for 'Keyword Arguments'. Now, can anyone summarize how we would use it?

Student 2
Student 2

We define the function with `**kwargs`, call it with named arguments, and it gathers them into a dictionary format.

Teacher
Teacher

Precisely! This gives us great flexibility in our functions.

Advantages of Using Variable-Length Arguments

Unlock Audio Lesson

0:00
Teacher
Teacher

Now that we’ve seen `*args` and `**kwargs`, let's talk about why we use these features. Why do you think they might be useful in real-life programming?

Student 3
Student 3

It makes functions flexible, allowing them to handle different scenarios!

Teacher
Teacher

Exactly! They let you define functions that can catch various input formats which aids in writing cleaner and more modular code. What’s another advantage?

Student 4
Student 4

We don't have to change the function definition every time we need to add more arguments.

Teacher
Teacher

Yes! This supports code maintenance and evolution. Let’s have a brief quiz: Can anyone tell me a key point about using `*args`?

Student 1
Student 1

It can handle any number of positional inputs!

Teacher
Teacher

Correct! And what about `**kwargs`?

Student 2
Student 2

It collects keyword arguments as a dictionary!

Teacher
Teacher

Excellent! Great discussion today, everyone!

Introduction & Overview

Read a summary of the section's main ideas. Choose from Basic, Medium, or Detailed.

Quick Overview

Variable-length arguments allow functions in Python to accept any number of positional or keyword arguments, providing flexibility in function design.

Standard

In this section, we explore variable-length arguments in Python, specifically arbitrary positional arguments using args and arbitrary keyword arguments using *kwargs. These feature enable more dynamic function interfaces, allowing greater versatility in argument handling.

Detailed

Variable-Length Arguments

In Python, functions can often be created to handle more flexible argument passing methods through the use of variable-length arguments. This allows functions to accept a variable number of positional and keyword arguments. We cover two main mechanisms here:

Arbitrary Positional Arguments (*args)

Using *args, a function can accept any number of positional arguments. All arguments passed are captured in a tuple, which can be manipulated within the function. For example:

Code Editor - python

This approach is particularly useful when the number of inputs isn't predetermined.

Arbitrary Keyword Arguments (**kwargs)

With **kwargs, a function can receive any number of keyword arguments, which are captured in a dictionary, allowing named parameters to be passed. For instance:

Code Editor - python

This feature enhances the function's flexibility and can simplify handling of optional parameters. Overall, understanding and utilizing *args and **kwargs promotes cleaner and more manageable code.

Youtube Videos

Complete Playlist of AI Class 12th
Complete Playlist of AI Class 12th

Audio Book

Dive deep into the subject with an immersive audiobook experience.

Arbitrary Positional Arguments (*args)

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

• Arbitrary Positional Arguments *args:

def total_marks(*marks):
return sum(marks)

total = total_marks(90, 85, 75)

Detailed Explanation

In Python, you can define functions that can accept a variable number of arguments using a special syntax. This is done with *args, where 'args' is a name you can choose. When you define a function like this, it allows you to pass any number of positional arguments to the function. Inside the function, these arguments are accessible as a tuple.

For example, in the function 'total_marks(*marks)', the variable 'marks' can accept multiple values. When you call 'total_marks(90, 85, 75)', it computes the sum of those marks. The function 'sum(marks)' calculates the total of all the arguments passed.

Examples & Analogies

Think of args like a potluck dinner where each guest can bring their own dish. You don’t know how many guests will come or what they will bring, but you still want to prepare a big meal. Similarly, when you use args, you can take in any number of arguments, just like collecting dishes from the guests to create one big dinner.

Arbitrary Keyword Arguments (**kwargs)

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

• Arbitrary Keyword Arguments **kwargs:

def display_info(**kwargs):
for key, value in kwargs.items():
print(f"{key} : {value}")

display_info(name="AI", year=2025)

Detailed Explanation

Like args for positional arguments, Python provides a way to handle arbitrary keyword arguments using *kwargs. This allows functions to accept any number of keyword arguments (those passed as key-value pairs). Inside the function, these arguments are organized into a dictionary.

In the 'display_info(**kwargs)' function, each keyword argument you pass is collected into the 'kwargs' dictionary. For example, calling 'display_info(name="AI", year=2025)' creates a dictionary with two key-value pairs. The for loop then iterates through this dictionary and prints each key and its corresponding value.

Examples & Analogies

Consider **kwargs as writing a letter where you can include any information you want, like your name, address, or date, without a fixed format. Everyone writes their letter differently, but when you receive it, you can read each part because you can identify what each piece of information represents, just like the function can access each keyword argument.

Definitions & Key Concepts

Learn essential terms and foundational ideas that form the basis of the topic.

Key Concepts

  • *args: Allows passing a variable number of positional arguments to a function.

  • **kwargs: Allows passing a variable number of keyword arguments to a function.

Examples & Real-Life Applications

See how the concepts apply in real-world scenarios to understand their practical implications.

Examples

  • Example of *args: total = total_marks(70, 80, 90) where total becomes 240.

  • Example of **kwargs: display_info(name='AI', year=2025') prints 'name : AI' and 'year : 2025'.

Memory Aids

Use mnemonics, acronyms, or visual cues to help remember key information more easily.

🎵 Rhymes Time

  • With *args you can share, numbers without care; just pass as you please, as many as you dare!

📖 Fascinating Stories

  • Imagine you are at a feast, collecting many dishes. *args allows you to take as many dishes as you like. Meanwhile, **kwargs gives you a menu to select from by name.

🧠 Other Memory Gems

  • Remember: * for *args means 'all about positions'; `` for kwargs means 'keys with the definition'.

🎯 Super Acronyms

Acronym for remembering

  • 'Flexible Functions'
  • where F is for *args (Flexible Positional) and K is for **kwargs (Keyword Kind).

Flash Cards

Review key concepts with flashcards.

Glossary of Terms

Review the Definitions for terms.

  • Term: *args

    Definition:

    A special syntax in Python that allows a function to accept a variable number of positional arguments.

  • Term: **kwargs

    Definition:

    A special syntax in Python that allows a function to accept a variable number of keyword arguments.