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

Lists

The document provides an introduction to lists, loops, and functions in Python. It explains how to create and manipulate lists, iterate using for and while loops, and define and call functions with various types of arguments. The summary emphasizes the importance of these concepts for organizing and reusing code.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Lists

The document provides an introduction to lists, loops, and functions in Python. It explains how to create and manipulate lists, iterate using for and while loops, and define and call functions with various types of arguments. The summary emphasizes the importance of these concepts for organizing and reusing code.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

1.

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:

# Creating a list of numbers


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

# Creating a list of mixed data types


mixed_list = [1, "Hello", 3.14, True]

Accessing Elements:

 Indexing: Access elements by their index. Indexing starts from 0.

# Accessing the first element


print(numbers[0]) # Output: 1

# Accessing the last element


print(mixed_list[-1]) # Output: True

 Slicing: Access a range of elements.

# Access elements from index 1 to 3 (exclusive)


print(numbers[1:3]) # Output: [2, 3]

Modifying Lists:

 Adding Elements:
o append(): Adds an element at the end.

numbers.append(6) # [1, 2, 3, 4, 5, 6]

o insert(): Adds an element at a specified position.

numbers.insert(1, 1.5) # [1, 1.5, 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).

numbers.pop() # Output: 6, List after pop: [1, 2, 3, 4, 5]


 List Comprehension: A concise way to create lists.

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).

# Iterating through a list


for num in numbers:
print(num) # Prints each number in the list

 Range Function: Useful for generating a sequence of numbers.

# Looping through a range of numbers


for i in range(5): # range(5) generates numbers 0 to 4
print(i) # Prints numbers 0 to 4

While Loop:

 Repeats a block of code as long as a condition is true.

# Using a while loop to print numbers from 1 to 5


counter = 1
while counter <= 5:
print(counter)
counter += 1 # Increment counter

Loop Control Statements:

 break: Terminates the loop.

for num in numbers:


if num == 3:
break # Exit the loop when num is 3
print(num) # Output: 1, 2

 continue: Skips the current iteration and proceeds to the next.

for num in numbers:


if num == 3:
continue # Skip the iteration when num is 3
print(num) # Output: 1, 2, 4, 5

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:

# Defining a simple function


def greet(name):
"""This function prints a greeting message."""
print(f"Hello, {name}!")

Calling a Function:

# Calling the greet function


greet("Alice") # Output: Hello, Alice!

Function Parameters:

 Positional Arguments:

def add(a, b):


return a + b

result = add(3, 5) # Output: 8

 Keyword Arguments:

def multiply(a, b=2):


return a * b

result = multiply(3) # Output: 6, as b defaults to 2

 Arbitrary Arguments:
o Using *args for multiple positional arguments.

def sum_all(*args):
return sum(args)

result = sum_all(1, 2, 3, 4) # Output: 10

o Using **kwargs for multiple keyword arguments.

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

print_info(name="Alice", age=30) # Output: name: Alice, age: 30

Return Statement:

 Functions can return a value using the return statement.

def square(x):
return x**2

result = square(4) # Output: 16

Lambda Functions:
 Anonymous functions defined using the lambda keyword.

# A lambda function to calculate the square of a number


square = lambda x: x**2

result = square(5) # Output: 25

Higher-Order Functions:

 Functions that take other functions as arguments or return functions.

# A function that takes another function as an argument


def apply_function(func, value):
return func(value)

result = apply_function(square, 3) # Output: 9

4. Putting It All Together:

Example: A Function that Processes a List with Loops

# Function to find the sum of all even numbers in a list


def sum_of_evens(numbers):
total = 0
for num in numbers:
if num % 2 == 0:
total += num
return total

# Using the function


nums = [1, 2, 3, 4, 5, 6]
result = sum_of_evens(nums) # Output: 12 (2 + 4 + 6)

Summary:

 Lists allow for storing and manipulating collections of items.


 Loops enable repeated execution of code blocks.
 Functions help in creating reusable blocks of code for specific tasks.

You might also like