Skip to document

W2 Python study material

The material will provide detailed explanation on the different types...
Course

python programming (cs8151)

86 Documents
Students shared 86 documents in this course
University

Anna University

Academic year: 2023/2024

Comments

Please sign in or register to post comments.

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

  1. Strings

  2. A sequence of one or more characters.

  3. Can contain letters, numbers, and symbols.

  4. Can be a constant or a variable.

  5. Strings in Python are immutable.

  6. Created by enclosing a sequence of characters inside single, double, or triple quotes.

  7. Example: strsample = "learning" > when printed, this outputs "learning".

  8. Lists

1. Created by placing a sequence inside square brackets.

  1. Can contain elements of multiple data types.

  2. Can have duplicate values with distinct positions.

  3. Mutable can be altered postcreation.

  4. Example: lstsample = [1, 2, "a", "sam", 2]

  5. Arrays

  6. Collections of items stored at contiguous memory locations.

  7. Used to store items of the same data type.

  8. Created in Python by importing the array module.

  9. Example of creating an array with integers: array_sample = array(i, [1, 2, 3, 4])

  10. Tuples

  11. Similar to lists but immutable (cannot be altered postcreation).

  12. Created by placing elements inside parentheses and separated by commas.

  13. Can be created without parentheses, known as tuple packing.

  14. Can contain multiple data types.

  15. Example: sample_tuple = 1, "a", 2

  16. Dictionaries

  17. Unordered collections of data values used to store data like a map.

  18. Holds key-value pairs.

  19. Values can be duplicated, but keys must be unique.

  20. Created by placing sequences of elements inside curly braces.

  21. Can also be created using the builtin dict function.

  22. Example: dict_sample = {1: "first", 2: "second"}

  23. Sets

  24. Collections of various elements with an undefined order.

  25. Immutable data types can be set elements.

  26. Lists and sets themselves cannot be set elements.

  27. Created by placing elements inside curly brackets or using the set function.

  28. Example: set_sample = {1, "a", 2}

  29. Range

  30. A builtin Python functions.

  31. Commonly used in for looping.

  32. Takes three arguments: start value, stop value, and step size.

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

  1. Find index of l: Output is 0.
  2. For substring ning, output is 4 (representing index of n).
  3. Accessing via square brackets for POSITION: strsample[7] gives g.
  4. strsample[-9]: will throw index error, because strsample[-8] = ‘l’, first alphabet of ‘learning’

List Indexing:

  1. List example: lstsample = [1, 2, ‘a’, ‘sam’, 2] with elements like numbers and strings.
  2. 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.
  3. Use square brackets to fetch an element by its index: lstsample[2] gives a.
  4. lstsample[-2] will give 2. Array Indexing:
  5. 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'.

  1. 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:

  1. Introduction to Slicing
    1. Slicing is a technique to retrieve a subset of a sequence.
    2. A slice object is used to slice a given sequence.
    3. The sequence can be strings, tuples, bytes, lists, ranges, or any object which supports the sequence protocol.
  2. 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'
  3. Alternative Slicing Methods
    1. Another method for slicing elements is using the square bracket notation without the slice function.
    2. 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

  1. Arrays and ranges support similar slicing operations as lists and strings.

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

  3. Fundamental Sequence Data Operations: Concatenation & Multiplication Concatenation:

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

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

  1. 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.
  2. 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
  3. len() Method Returns the number of elements in an object. Example: len(strsample) returns the length of strsample.
  4. reverse() Method Reverses the order of a list.
  5. clear() Method Removes all items from a specified object. Applies to lists, dictionaries, and sets.
  6. 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

  1. 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.
  2. 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.
  3. 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.
  4. Accessing NumPy and Installation:  NumPy needs to be installed to be imported and used.  Installation Command: pip install numpy
  5. 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

Was this document helpful?

W2 Python study material

Course: python programming (cs8151)

86 Documents
Students shared 86 documents in this course

University: Anna University

Was this document helpful?
NPTEL PYTHON FOR DATA SCIENCE OCTOBER-2023
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
1. Strings
1. A sequence of one or more characters.
2. Can contain letters, numbers, and symbols.
3. Can be a constant or a variable.
4. Strings in Python are immutable.
5. Created by enclosing a sequence of characters inside single, double, or triple
quotes.
6. Example: strsample = "learning" > when printed, this outputs "learning".
2. Lists
1. Created by placing a sequence inside square brackets.
2. Can contain elements of multiple data types.
3. Can have duplicate values with distinct positions.
4. Mutable can be altered postcreation.
5. Example: lstsample = [1, 2, "a", "sam", 2]
3. Arrays
1. Collections of items stored at contiguous memory locations.
2. Used to store items of the same data type.
3. Created in Python by importing the array module.
4. Example of creating an array with integers: array_sample = array(i, [1, 2, 3, 4])
4. Tuples
1. Similar to lists but immutable (cannot be altered postcreation).
2. Created by placing elements inside parentheses and separated by commas.
3. Can be created without parentheses, known as tuple packing.
4. Can contain multiple data types.
1