Key Python Unit 1 & 2 Questions
Key Python Unit 1 & 2 Questions
Python lists are mutable, ordered collections that support various methods for manipulation. Common methods include `.append()` to add elements, `.remove()` to delete a specific item, and `.pop()` to remove and return an item at a given index. Other useful methods are `.sort()` to sort the list and `.reverse()` to reverse its order. For instance, `fruits = ['apple', 'banana']`, `fruits.append('orange')` results in `['apple', 'banana', 'orange']`. `fruits.remove('banana')` results in `['apple', 'orange']`. These methods facilitate dynamic handling of collections .
Anonymous functions in Python are created using the `lambda` keyword, allowing for the quick definition of small functions without a name. These are particularly useful in higher-order functions like `map()`, `reduce()`, and `filter()`. `map()` applies a function to all items in an iterable, `filter()` filters items based on a function returning a Boolean, and `reduce()` (from the `functools` module) accumulates a result across an iterable. For example, using `map()`: `squared = map(lambda x: x*x, [1, 2, 3])` results in `[1, 4, 9]`. With `filter()`: `filtered = filter(lambda x: x > 2, [1, 2, 3])` gives `[3]`. Finally, `reduce()`: `from functools import reduce; result = reduce(lambda x, y: x+y, [1, 2, 3])` results in `6`. These tools provide elegant solutions for functional programming needs .
Dictionaries in Python are mutable data types that store key-value pairs. Methods such as `.get()` provide default values if a key is missing, `.keys()` and `.values()` return views of the keys and values, respectively, and `.items()` gives key-value pair views allowing for efficient iteration. `.update()` can merge another dictionary or key-value pairs into the dictionary. A typical use case is storing configuration parameters or aggregating counts, such as `config = {'setting1': True, 'setting2': False}` where `config.get('setting3', 'default')` ensures safe access. The method choices enable efficient, expressive management of associative data .
Python's basic operators include arithmetic and comparison operators. Arithmetic operators like `+`, `-`, `*`, `/`, and `%` perform calculations on numbers. For instance, `a + b` adds two numbers. Comparison operators such as `==`, `!=`, `>`, `<`, `>=`, and `<=` compare two values and return a Boolean. For example, `if a > b:` checks if 'a' is greater than 'b'. Here is a script example: `result = 5 + 3 * 2`. Another script for comparison could be `isEqual = (5 == 5)`, which evaluates to `True` .
Tuples in Python are immutable sequences used to store collections of items. Being immutable, tuple operations focus more on retrieval than modification. Key methods include `.count()`, which returns the number of occurrences of a specified value, and `.index()`, which finds the first occurrence of a value. A tuple can be sliced similarly to lists, using `tuple[start:stop]`. For example, `colors = ('red', 'blue', 'green')`, `colors.count('red')` returns `1`, and `colors.index('blue')` returns `1`. Due to their immutability, tuples can be used as keys in dictionaries .
Python offers a variety of operations and methods to manipulate strings. Common operations include concatenation using `+` and replication using `*`. Python strings provide methods like `.lower()` and `.upper()` to change case, `.strip()` to remove whitespace, and `.replace()` to substitute a substring. Additionally, `.find()` locates substrings, returning the index or `-1` if not found. The syntax generally follows `string.method(parameters)`. For example, `name = ' Alice '`, `name.strip()` returns `'Alice'`, and `name.replace('A', 'B')` returns `'Blice'`. These convenience methods facilitate efficient string manipulation .
Python is known for its simplicity, readability, and ease of learning due to its straightforward syntax that resembles the English language. It supports multiple programming paradigms, including procedural, object-oriented, and functional programming, which makes it versatile. Python is dynamically typed, meaning the type of a variable is determined at runtime, reducing the overhead of declaring variables' types. Python has a comprehensive standard library that supports many common programming tasks such as file I/O, system calls, and even Internet protocols, which allows developers to perform complex tasks using minimal code. Furthermore, Python's extensive third-party modules and easy integration with other languages add to its flexibility and capability as a modern programming language .
Python functions support several types of arguments: positional, keyword, default, and arbitrary. Positional arguments are the basic function inputs by order. Keyword arguments allow calling with named references, improving readability. Default arguments provide a fallback value if none is supplied, defined with `param=value`. Arbitrary arguments allow functions to accept varying input sizes with `*args` for non-keyword arguments and `**kwargs` for keyword variants, handling inputs as tuples and dictionaries respectively. For example, `def example(a, b=2, *args, **kwargs): pass` combines these types wherein `example(3)` uses defaults, `example(3, 4, 5)` uses additional, and `example(a=1, d=3, b=2)` demonstrates keyword and default interactions, illustrating flexible calling conventions .
Python's control flow is managed with conditional statements such as `if`, `elif`, and `else`, which execute code blocks based on Boolean conditions. For instance, an `if` statement can be used to execute a block if its condition is true. Looping constructs include `for` and `while` loops. `for` loops iterate over items of a collection, whereas `while` loops run as long as a condition is true. Nested loops allow complex iterations. For example, an `if` statement could look like: `if x > 0: print("Positive")`. A `for` loop can iterate through a list like `for item in items: print(item)`, and a `while` loop might be `while x > 0: x -= 1` .
Python has several standard data types, including integers for whole numbers, floats for decimal numbers, and strings for text. Integers are immutable, allowing unbounded precision. Floats represent real numbers but are subject to rounding errors. Strings, also immutable, store text and support various methods for manipulation. Lists are ordered collections of items that are mutable, meaning they can be modified after creation. Tuples are similar to lists but immutable. Dictionaries store key-value pairs and are highly efficient for lookups. Lastly, sets are unordered collections of unique items useful for membership testing and eliminating duplicates. For example, an integer `x = 5`, a float `y = 3.14`, a string `greeting = "Hello"`, a list `fruits = ['apple', 'banana']`, a tuple `coordinates = (10, 20)`, a dictionary `student = {'name': 'John', 'age': 25}`, and a set `numbers = {1, 2, 3}` .