0% found this document useful (0 votes)
17 views

Python Day 3 (2 Day Project)

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Python Day 3 (2 Day Project)

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Python

Notes
Data Structures

1. Lists

- Lists are ordered, mutable collections of items.

- Items in a list can be of any data type and lists can contain a mix of different types.

- Lists are defined using square brackets: my_list = [1, 2, 3, 'a', 'b', 'c']

- Common list operations:

- Accessing elements: my_list[0] (returns first element)

- Slicing: my_list[1:3] (returns a new list with elements at index 1 and 2)

- Modifying elements: my_list[0] = 10 (changes first element to 10)

- Appending: my_list.append(4) (adds 4 to the end of the list)

- Extending: my_list.extend([5, 6]) (adds multiple elements to the end)

- Inserting: my_list.insert(1, 'x') (inserts 'x' at index 1)

- Removing: my_list.remove('a') (removes the first occurrence of 'a')

- Popping: my_list.pop(2) (removes and returns the element at index 2)

- Checking membership: 'a' in my_list (returns True if 'a' is in the list)

- Iterating: for item in my_list: print(item)

2. Tuples

- Tuples are ordered, immutable collections of items.

- Defined using parentheses: my_tuple = (1, 2, 3, 'a', 'b', 'c')


- Tuples support similar operations as lists except for modifications.

- Common tuple operations:

- Accessing elements: my_tuple[0]

- Slicing: my_tuple[1:3]

- Checking membership: 'a' in my_tuple

- Iterating: for item in my_tuple: print(item)

- Tuples can be used as keys in dictionaries because they are immutable.

3. Dictionaries

- Dictionaries are unordered collections of key-value pairs.

- Defined using curly braces: my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}

- Keys must be unique and immutable (e.g., strings, numbers, tuples).

- Values can be of any data type and can be duplicated.

- Common dictionary operations:

- Accessing values: my_dict['name'] (returns 'John')

- Modifying values: my_dict['age'] = 26 (changes age to 26)

- Adding new key-value pairs: my_dict['email'] = 'john@example.com'

- Removing key-value pairs: del my_dict['city'] (removes the key 'city')

- Checking membership: 'name' in my_dict (returns True if 'name' is a key)

- Iterating keys: for key in my_dict: print(key)

- Iterating values: for value in my_dict.values(): print(value)

- Iterating key-value pairs: for key, value in my_dict.items(): print(key, value)

4. Sets

- Sets are unordered collections of unique items.

- Defined using curly braces: my_set = {1, 2, 3, 'a', 'b', 'c'}

- Common set operations:


- Adding elements: my_set.add(4)

- Removing elements: my_set.remove('a')

- Checking membership: 'a' in my_set

- Iterating: for item in my_set: print(item)

- Set operations (union, intersection, difference):

- Union: set1.union(set2) or set1 | set2

- Intersection: set1.intersection(set2) or set1 & set2

- Difference: set1.difference(set2) or set1 - set2

- Converting list to set: set(my_list) (removes duplicates)

Functions

1. Defining and Calling Functions

- Functions are defined using the def keyword:

python

def my_function():

print("Hello, World!")

- Functions are called using parentheses: my_function()

2. Function Arguments and Return Values

- Functions can accept parameters:

python

def greet(name):

print(f"Hello, {name}!")

greet('Alice')

- Functions can return values using the return keyword:


python

def add(a, b):

return a + b

result = add(2, 3)

3. Default and Keyword Arguments

- Default arguments are specified in the function definition:

python

def greet(name, greeting="Hello"):

print(f"{greeting}, {name}!")

greet('Bob')

greet('Alice', 'Hi')

- Keyword arguments are passed by name:

python

def add(a, b):

return a + b

result = add(b=3, a=2)

4. Variable-Length Arguments

- Use args for variable-length positional arguments:

python

def sum(args):

return sum(args)

result = sum(1, 2, 3, 4)
- Use kwargs for variable-length keyword arguments:

python

def print_info(kwargs):

for key, value in kwargs.items():

print(f"{key}: {value}")

print_info(name='John', age=25, city='New York')

5. Lambda Functions

- Lambda functions are small anonymous functions defined with the lambda keyword:

python

add = lambda x, y: x + y

result = add(2, 3)

- Often used for short, throwaway functions in higher-order functions like map, filter, and
sorted:

python

numbers = [1, 2, 3, 4, 5]

squared = map(lambda x: x 2, numbers)

even_numbers = filter(lambda x: x % 2 == 0, numbers)

6. Scope and Lifetime of Variables

- Variables defined inside a function are local to that function:

python

def my_function():
x = 10 Local variable

- Variables defined outside any function are global:

python

x = 10 Global variable

def my_function():

print(x) Accesses global variable

my_function()

- Use the global keyword to modify a global variable inside a function:

python

x = 10

def my_function():

global x

x = 20

my_function()

print(x) Outputs: 20

7. Recursive Functions

- Functions that call themselves are known as recursive functions.

- Must have a base case to stop recursion:

python

def factorial(n):

if n == 0:

return 1

else:
return n factorial(n - 1)

result = factorial(5)

Task 4

Here are some questions related to the topics of data structures and functions in Python:

Data Structures

1. Lists

1. Create a list of the first 10 positive integers. Print the list.

2. How do you access the third element in a list called my_list?

3. Write a Python function to remove all even numbers from a list.

4. What is the output of the following code?

python

my_list = [1, 2, 3, 4, 5]

my_list[2] = 10

print(my_list)

5. Write a Python program to concatenate two lists and sort the result.

2. Tuples

1. Create a tuple containing a mix of integers and strings. Print the tuple.

2. How do you access the last element of a tuple called my_tuple?

3. Write a function that accepts a tuple of numbers and returns the sum of all the numbers.

4. What is the output of the following code?

python

my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[1:4])

5. Can you modify a tuple after it has been created? Explain with an example.

3. Dictionaries

1. Create a dictionary with keys as names and values as ages. Print the dictionary.

2. How do you access the value associated with the key 'age' in a dictionary called person?

3. Write a Python function to update the value of a given key in a dictionary.

4. What is the output of the following code?

python

my_dict = {'a': 1, 'b': 2, 'c': 3}

del my_dict['b']

print(my_dict)

5. Write a program to merge two dictionaries.

4. Sets

1. Create a set of unique integers from a list containing duplicate values. Print the set.

2. How do you check if an element exists in a set called my_set?

3. Write a function to find the intersection of two sets.

4. What is the output of the following code?

python

set1 = {1, 2, 3}

set2 = {3, 4, 5}

print(set1.union(set2))

5. Write a program to remove an element from a set if it is present.


Functions

1. Defining and Calling Functions

1. Write a function greet that takes a name as an argument and prints "Hello, <name>!".

2. How do you call a function named calculate that takes two arguments a and b?

3. Write a Python function that returns the square of a number.

2. Function Arguments and Return Values

1. Write a function multiply that takes two numbers and returns their product.

2. What is the output of the following code?

python

def subtract(a, b):

return a - b

result = subtract(10, 5)

print(result)

3. Write a function that takes a list of numbers and returns their average.

3. Default and Keyword Arguments

1. Write a function greet with a default argument greeting="Hello" and a name. It should print
the greeting followed by the name.

2. How do you call a function add with keyword arguments a=5 and b=3?

3. Write a function divide with two arguments a and b where b has a default value of 1. It
should return the result of division of a by b.

4. Variable-Length Arguments

1. Write a function sum_all that takes any number of arguments and returns their sum.

2. What is the output of the following code?


python

def print_args(args):

for arg in args:

print(arg)

print_args(1, 2, 3)

3. Write a function print_info that takes any number of keyword arguments and prints them.

5. Lambda Functions

1. Write a lambda function that takes two numbers and returns their difference.

2. How do you use a lambda function with the map function to square each number in a list?

3. Write a lambda function to filter even numbers from a list using the filter function.

6. Scope and Lifetime of Variables

1. What is the difference between a local and a global variable? Provide an example.

2. Write a function that modifies a global variable inside the function.

3. Explain the output of the following code:

python

x = 10

def my_function():

x=5

print(x)

my_function()

print(x)

7. Recursive Functions
1. Write a recursive function to calculate the factorial of a number.

2. What is the base case in a recursive function? Provide an example.

3. Write a recursive function to compute the nth Fibonacci number.

These questions cover the key concepts and operations for data structures and functions in
Python. They are designed to test both theoretical understanding and practical application
skills.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy