Container objects and functions in python

Container objects and functions in python

Containers in Python are data structures that are used to store and organize multiple values or objects. There are several built-in container types in Python, including lists, tuples, dictionaries, and sets.

1. Lists:

A list is a collection of items that are ordered and changeable. Lists are created using square brackets [] and can contain any data type, including other lists.

2. Tuples:

A tuple is similar to a list, but it is immutable, meaning its elements cannot be changed after creation. Tuples are created using parentheses ().

3. Dictionaries:

A dictionary is a collection of key-value pairs. Dictionaries are unordered, and their keys are unique. They are created using curly braces {}.

4. Sets:

A set is an unordered collection of unique elements. Sets are created using curly braces {} or the set() constructor.

Functions in Python:

Functions in Python are reusable blocks of code that perform a specific task. They are defined using the def keyword, followed by the function name, parameters (if any), and a colon :. Functions can return values using the return statement. Here’s an example of a simple function:

def greet(name):
    """This function greets the person passed in as a parameter.""" 
    return f"Hello, {name}!"
# Calling the function
message = greet("Alice")
print(message)

In this example, we defined a function called greet that takes a parameter name and returns a greeting message.

def find_max(numbers):
     """This function finds the maximum value in a list of numbers.""" 
    if not numbers:
       return None 
    max_num = numbers[0] 
    for num in numbers: 
        if num > max_num:
             max_num = num
     return max_num 
# Calling the function 
numbers = [5, 2, 9, 1, 7] 
max_value = find_max(numbers) 
print(f"The maximum value is: {max_value}")

Output:

The maximum value is: 9

In this example, the find_max function takes a list of numbers as a parameter and returns the maximum value found in the list.

These examples should help college students understand the concepts of containers and functions in Python. Containers are used to store and organize data, while functions are used to encapsulate and reuse blocks of code.

we will go through some more codes in Jupyter notebook below:

The python code block is embedded here in the below section. please scroll through the embedded page to see the complete content.

after completing these codes, go through next lesson on pandas: Pandas introduction

Was this article helpful?
YesNo

Leave a Comment