Python Essentials Part 3

PYTHON LISTS AND ARRAYS

Python Lists

A list in Python is a collection that is ordered, changeable (mutable), and allows duplicate elements. Lists are one of the most commonly used data structures and can hold multiple data types, such as integers, strings, floats, or even other lists.

Python Arrays

In Python, the list structure itself is often used in place of arrays. However, the array module can be used if you want to specifically work with arrays of uniform data types. Arrays in Python are more restricted than lists because they can only hold elements of the same type (e.g., only integers or only floats).

Key Differences Between Lists and Arrays:

  • Lists can contain elements of different data types, while arrays require all elements to be of the same type.

  • Lists are more flexible and widely used in Python, whereas arrays are used when you need more control over memory and performance for uniform data types.

Python lists are versatile, making them suitable for most use cases, but arrays can be useful for specialized applications involving numerical data.

Python Lists In-depth

1. Creating a List

Lists are created by placing comma-separated elements inside square brackets [].

my_list = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
mixed_list = [1, "hello", 3.5]

2. Accessing List Elements
List elements are accessed using their index, which starts at 0 for the first element.

fruits = ["apple", "banana", "cherry"]

# Accessing elements
print(fruits[0])  # Output: apple
print(fruits[2])  # Output: cherry

Negative indexing can be used to access elements from the end of the list.

print(fruits[-1])  # Output: cherry (last element)

3. Modifying a List
Since lists are mutable, you can change the value of specific elements, add new elements, or remove elements.

fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry"
print(fruits)  # Output: ['apple', 'blueberry', 'cherry']

Appending Elements:

fruits.append("orange")
print(fruits)  # Output: ['apple', 'blueberry', 'cherry', 'orange']

Inserting Elements:

fruits.insert(1, "mango")
print(fruits)  # Output: ['apple', 'mango', 'blueberry', 'cherry', 'orange']

Removing Elements:

fruits.remove("blueberry")
print(fruits)  # Output: ['apple', 'mango', 'cherry', 'orange']

List Methods

Python provides many built-in methods for manipulating lists:

  • append(): Adds an element to the end of the list.

  • insert(): Adds an element at a specific position.

  • remove(): Removes the first occurrence of an element.

  • pop(): Removes an element at a given position (if no index is specified, removes the last element).

  • reverse(): Reverses the order of the list.

  • sort(): Sorts the list in ascending order.

Python Arrays In-depth

1. Creating an Array

import array as arr

my_array = arr.array('i', [1, 2, 3, 4, 5])  # 'i' stands for integer type

In the above example, 'i' is a type code that indicates the array will hold integers. Other common type codes include:

  • 'f' for float

  • 'd' for double

2. Array Methods

Arrays also support methods similar to lists:

  • append(): Adds an element to the end of the array.

  • insert(): Inserts an element at a specified index.

  • remove(): Removes the first occurrence of an element.

import array as arr

my_array = arr.array('i', [10, 20, 30])

# Append a new element
my_array.append(40)
print(my_array)  # Output: array('i', [10, 20, 30, 40])

# Remove an element
my_array.remove(20)
print(my_array)  # Output: array('i', [10, 30, 40])

Python Functions

A function is a block of reusable code that is designed to perform a specific task. Functions help make code modular and more organized by breaking down complex tasks into smaller, manageable parts.


1. Defining a Function

Functions in Python are defined using the def keyword, followed by the function name, parentheses (), and a colon :. Inside the function, you can write the code that gets executed when the function is called.

Syntax:

def function_name(parameters):
    # Function body
    return value  # Optional

Example:

def greet(name):
    print(f"Hello, {name}!")

greet("Alice")  # Output: Hello, Alice!
  • In this example, the greet() function takes a parameter name and prints a greeting.

2. Return Values

Functions can return values using the return statement. This allows the function to pass results back to the caller.

Example:

def add(a, b):
    return a + b

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

3. Default Parameters

You can define default values for function parameters, making them optional when the function is called.

Example:

def greet(name="Guest"):
    print(f"Hello, {name}!")

greet()         # Output: Hello, Guest!
greet("John")   # Output: Hello, John!

4. Functions with Multiple Parameters

Functions can accept multiple parameters, allowing more complex operations.

Example:

def multiply(a, b):
    return a * b

print(multiply(4, 5))  # Output: 20

5. Functions with Variable-Length Arguments

Python allows you to pass a variable number of arguments to a function using *args for non-keyword arguments and **kwargs for keyword arguments.

Example:

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

print(sum_numbers(1, 2, 3, 4))  # Output: 10

Python Classes and Objects

Python is an object-oriented programming (OOP) language. This means that it allows the creation of reusable, modular pieces of code called classes that define the properties (attributes) and behavior (methods) of objects.


1. Defining a Class

A class is a blueprint for creating objects. It defines attributes (variables) and methods (functions) that the objects will have.

Syntax:

class ClassName:
    def __init__(self, parameters):
        # Constructor
        self.attribute = value

    def method(self):
        # Method
        pass

The __init__() method is the constructor, which is called when an object is created from a class. It initializes the object's attributes.

Example:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

# Creating an object of the class Person
person1 = Person("Alice", 30)
person1.greet()  # Output: Hello, my name is Alice and I am 30 years old.

2. Creating Objects

An object is an instance of a class. Once you have defined a class, you can create objects of that class by calling the class name as if it were a function.

Example:

person2 = Person("Bob", 25)
person2.greet()  # Output: Hello, my name is Bob and I am 25 years old.

Each object can have different values for the attributes defined in the class.


3. Methods in Classes

Methods are functions defined inside a class that operate on objects. The first parameter of a method is always self, which refers to the instance of the class (the object calling the method).

Example:

class Car:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model

    def details(self):
        print(f"This car is a {self.brand} {self.model}")

car1 = Car("Toyota", "Corolla")
car1.details()  # Output: This car is a Toyota Corolla

4. Class Attributes vs Instance Attributes

  • Instance attributes: These are specific to each object and are typically defined in the __init__() method.

  • Class attributes: These are shared by all objects of the class.

Example of Class Attribute:

class Dog:
    species = "Canine"  # Class attribute

    def __init__(self, name):
        self.name = name  # Instance attribute

dog1 = Dog("Buddy")
dog2 = Dog("Rex")

print(dog1.species)  # Output: Canine
print(dog2.species)  # Output: Canine

5. Inheritance in Classes

Python allows classes to inherit properties and methods from other classes. This is called inheritance, and it allows code reusability.

Example:

class Animal:
    def __init__(self, name):
        self.name = name

    def sound(self):
        print("Some generic animal sound")

class Dog(Animal):  # Dog inherits from Animal
    def sound(self):
        print("Bark")

# Creating an instance of Dog
dog = Dog("Buddy")
dog.sound()  # Output: Bark

In this example, the Dog class inherits from the Animal class but overrides the sound() method to provide its own implementation.


Key Points:

  • Functions allow you to define reusable pieces of code.

  • Classes provide a blueprint for creating objects, encapsulating data (attributes) and functionality (methods).

  • Objects are instances of classes, and each object can have its own unique attributes.

  • Inheritance allows one class to inherit the properties and methods of another, making the code more modular and reusable.

Python's support for functions, classes, and objects provides the foundation for both procedural and object-oriented programming approaches.