- Information
- AI Chat
W2 Python study material
python programming (cs8151)
Anna University
Recommended for you
Preview text
WEEK 2: VIDEO 1:
SEQUENCE DATA TYPES IN PYTHON
Sequence data types allow the creation or storage of multiple values in an organized and efficient manner.
Types of Sequence Data
Strings
A sequence of one or more characters.
Can contain letters, numbers, and symbols.
Can be a constant or a variable.
Strings in Python are immutable.
Created by enclosing a sequence of characters inside single, double, or triple quotes.
Example: strsample = "learning" > when printed, this outputs "learning".
Lists
1. Created by placing a sequence inside square brackets.
Can contain elements of multiple data types.
Can have duplicate values with distinct positions.
Mutable can be altered postcreation.
Example: lstsample = [1, 2, "a", "sam", 2]
Arrays
Collections of items stored at contiguous memory locations.
Used to store items of the same data type.
Created in Python by importing the array module.
Example of creating an array with integers: array_sample = array(i, [1, 2, 3, 4])
Tuples
Similar to lists but immutable (cannot be altered postcreation).
Created by placing elements inside parentheses and separated by commas.
Can be created without parentheses, known as tuple packing.
Can contain multiple data types.
Example: sample_tuple = 1, "a", 2
Dictionaries
Unordered collections of data values used to store data like a map.
Holds key-value pairs.
Values can be duplicated, but keys must be unique.
Created by placing sequences of elements inside curly braces.
Can also be created using the builtin dict function.
Example: dict_sample = {1: "first", 2: "second"}
Sets
Collections of various elements with an undefined order.
Immutable data types can be set elements.
Lists and sets themselves cannot be set elements.
Created by placing elements inside curly brackets or using the set function.
Example: set_sample = {1, "a", 2}
Range
A builtin Python functions.
Commonly used in for looping.
Takes three arguments: start value, stop value, and step size.
Example: range(1, 12, 4) > outputs values 1, 5, and 9.
Non sequential Data Types 5. Dictionaries and Sets 6. Considered containers for nonsequential data.
- Find index of l: Output is 0.
- For substring ning, output is 4 (representing index of n).
- Accessing via square brackets for POSITION: strsample[7] gives g.
- strsample[-9]: will throw index error, because strsample[-8] = ‘l’, first alphabet of ‘learning’
List Indexing:
- List example: lstsample = [1, 2, ‘a’, ‘sam’, 2] with elements like numbers and strings.
- Find index of sam: lstsample(‘sam’) : Output is 3, because index corresponds to 1 is 0, and 2 is 1, and index corresponds to ‘sam’ is 3.
- Use square brackets to fetch an element by its index: lstsample[2] gives a.
- lstsample[-2] will give 2. Array Indexing:
- Consider an example, from array import * // missing * will throw syntax error arraysample = array (‘i’, [1, 2, 3, 4]) // omitting ‘ will throw Type error, “argument 1 must be Unicode character, not int for x in arrsample : print (x)
will give output 1 2 3 4 2. arrsample[0] will give 1 3. Arrays can also utilize negative indexing. arrsample[-2] will give 3 Tuple Indexing: Analysis of tupsample = (1, 2, 3, 4, 'py'): Name: The tuple is assigned to the variable named tupsample. Content:
Integers: The tuple contains four integers: 1, 2, 3, and 4.
String: The last item in the tuple is a string 'py'.
- Accessing elements print(tupsample[0]) # Output: 1 print(tupsample[4]) # Output: 'py' Tuple Operations: Concatenation: another_tuple = (5, 6) combined = tupsample + another_tuple print(combined) # Output: (1, 2, 3, 4, 'py', 5, 6) Repetition:
python repeated = tupsample * 2 print(repeated) # Output: (1, 2, 3, 4, 'py', 1, 2, 3, 4, 'py') Membership Test: print(3 in tupsample) # Output: True
Similar to lists and arrays, but contains immutable elements. 5. Set Indexing: Indexing is not supported for sets as they are nonsequential data containers. Set objects are not subscriptable. 6. Dictionary Indexing: Dictionaries consist of key-value pairs. Elements are accessed using keys, not indexes. They are not held in any order. Example: dictsample = {1:'GOLD', 'SILVER':2, 3:'BRONZE'} // declaration of a dictionary
dictsample[1] will throw Output 'GOLD'
dictsample['SILVER'] will throw Output 2 7. Range Indexing: rangesample = range (0, 10, 2)
WEEK 2: VIDEO 3:
Sequence Data Operations:
- Introduction to Slicing
- Slicing is a technique to retrieve a subset of a sequence.
- A slice object is used to slice a given sequence.
- The sequence can be strings, tuples, bytes, lists, ranges, or any object which supports the sequence protocol.
- Basic Syntax of Slicing The slice object represents the indices specified by the range function given the start, stop, and step value. Syntax for the slice object: slice(start, stop, step) start: Starting integer from where the slicing of the object begins. stop: Ending integer until which the slicing takes place, but it stops at the index (n - 1). step: Determines the increment between each index for slicing. Defaults to 1 if not provided. Example of Slicing: Given a string strsample with the value "learning": Using strsample[slice(1, 4, 2)] produces the output "er". [using the slice object within SQUARE brackets] Explanation: Slicing started from index 1 (e) and ended at index 3 (a), but only every 2nd character is considered; hence the result is "er". strsample = "learning" strsample[0,5,2] strsample[slice(0,5,2)] will throw the output : 'lan'
- Alternative Slicing Methods
- Another method for slicing elements is using the square bracket notation without the slice function.
- Using the colon operator inside square brackets allows for slicing:
[:] : Retrieves the entire string or sequence. [: n] : Retrieves from the start up to but not including index n. [m:] : Retrieves from index m to the end.
[m: n]: Retrieves from index m up to but not including index n. 3. Limitations of Slicing Not all data structures support slicing. Dictionaries: Do not support slicing due to their key value structure and lack of indexing. Sets: Also do not support slicing since elements inside sets are not indexed. 4. Slicing in Arrays and Ranges
Arrays and ranges support similar slicing operations as lists and strings.
Negative indexing can be used to count from the end of the sequence. Examples: Using arr[:n] retrieves elements from the start up to but not including index n. Using arr[n:] retrieves the last n elements.
Fundamental Sequence Data Operations: Concatenation & Multiplication Concatenation:
Use the + operator to join multiple sequences together. Example: "learning" + " python" produces "learning python". Multiplication: generally used to repeat a sequence a specific number of times.
String Formatting using format() Allows for multiple substitutions and value formatting in strings. Syntax involves placeholders (curly braces {}). Example: "{} Private. {}".format("Geeta", "Limited") produces "Geeta Private. Limited".
IV. Understanding Methods and Functions for a Variable
- The dir() function lists all methods and functions available for a specific data type. Example: dir(name) returns a list of methods for a string variable name.
- help() provides detailed documentation on data types or methods. Example: help(str) provides details about the find method for strings. Additional Methods for Sequential Data
- len() Method Returns the number of elements in an object. Example: len(strsample) returns the length of strsample.
- reverse() Method Reverses the order of a list.
- clear() Method Removes all items from a specified object. Applies to lists, dictionaries, and sets.
- append() and add() Methods Adds an element to the end of a list (append) or set (add). Example: Appending 3 to a list [1, 2] results in [1, 2, 3].
WEEK 2: VIDEO 5:
INTRODUCTION to NumPy
- What is NumPy? Definition: NumPy (Numerical Python) is a fundamental Python package for numerical computations. Use Case: It is essential for performing numerical operations in Python.
- Python Arrays vs NumPy Arrays: Python Array: Stores values of the same data type. Recall: A Python array can only have elements of a single data type. NumPy Array: A grid of values, all of the same type. Indexed by a tuple of nonnegative integers. Offers high performance and flexibility.
- Characteristics of NumPy Arrays: Dimensions: Number of array dimensions is known as its rank. Shape: A tuple indicating the size of an array in each dimension. Data Type: While NumPy tries to determine the data type when an array is created, it also allows for explicit specification.
- Accessing NumPy and Installation: NumPy needs to be installed to be imported and used. Installation Command: pip install numpy
- Basic Operations on NumPy Arrays: Importing NumPy: Often imported as np for convenience (import numpy as np). Creating Arrays: Use np() function. E., For a list of values 1 to 6: my_array = np(my_list, dtype=int) Reshaping Arrays: reshape method is used to reshape an arrays dimensions without changing its data. E., Reshaping an array to 3 rows and 2 columns: reshaped_array = my_array(3,2)
Creating Arrays using range and arange: range Function: Creates a sequence of values. Limitation: Doesn't show the values in the range, only the range itself. Usage: Mostly in control structures and for iteration. arange Function: From the Numpy library. Creates an array based on a sequence of values. Syntax: start value, stop value, incremental value. Note: If only one value (e., 24) is given, it acts as the stop value, and starts from 0, increments by 1, and stops at n1 (e., 23 for 24).
Arithmetic Operations on Numpy Arrays: Basics: Numpy supports element wise arithmetic operations on arrays. Arrays can be of float64 type (or other data types). Operations include addition, subtraction, multiplication, and division. Element wise Operations: Addition: Use numpy() or the + operator. It adds corresponding elements from two arrays. Subtraction: Use numpy() or the operator. Multiplication: Use * for elementwise multiplication. For dot product, use dot(). Example: x(y) or numpy(x, y). Division: Use / or numpy().
Other Functions on Numpy Arrays: Sum Function: Basic Usage: numpy(array_name)
Computes the sum of all elements in an array. Axes in Numpy: axis=0: Computes sum across rows (i., sum for each column). axis=1: Computes sum across columns (i., sum for each row).
Additional Built in Functions: Mean, median, etc.
array : Get the dimension of the array reshape(tuple) : Reshape the array based on the dimensions in the tuple range(n) : Create a sequence from 0 to n arange(n) : Create an array of sequence from 0 to n numpy() : Elementwise addition numpy() : Elementwise subtraction numpy() : Compute dot product between two arrays numpy(array_name) :Compute the sum of all elements in the array
W2 Python study material
Course: python programming (cs8151)
University: Anna University
- Discover more from: