Lists
Lists
Introduction to Lists
Definition:
A list in Python is a collection of items (elements) that are ordered and changeable. Lists
allow duplicate members and are one of the most versatile data structures in Python.
Creating a List:
Accessing Elements:
Modifying Lists:
Adding Elements:
o append(): Adds an element at the end.
numbers.append(6) # [1, 2, 3, 4, 5, 6]
Removing Elements:
o remove(): Removes the first occurrence of a value.
numbers.remove(1.5) # [1, 2, 3, 4, 5, 6]
o pop(): Removes and returns the element at a specified index (default is last
element).
python
Copy code
# Creating a list of squares
squares = [x**2 for x in range(1, 6)] # [1, 4, 9, 16, 25]
2. Introduction to Loops
For Loop:
Used for iterating over a sequence (e.g., list, tuple, dictionary, set, or string).
While Loop:
3. Introduction to Functions
Definition:
A function is a block of code that only runs when it is called. Functions help to organize and
reuse code.
Defining a Function:
Calling a Function:
Function Parameters:
Positional Arguments:
Keyword Arguments:
Arbitrary Arguments:
o Using *args for multiple positional arguments.
def sum_all(*args):
return sum(args)
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
Return Statement:
def square(x):
return x**2
Lambda Functions:
Anonymous functions defined using the lambda keyword.
Higher-Order Functions:
Summary: