Python Arrays Lecture Notes

Jul 23, 2024

Python Arrays Lecture Notes

Introduction to Arrays

  • Presenter: Ivan 20
  • Focus: Understanding arrays in Python.

Difference Between Lists, Tuples, and Arrays

  • Lists: Can hold mixed data types (integers, floats, strings).
  • Tuples: Immutable version of lists, also allows mixed values.
  • Arrays: All elements must be of the same type (e.g., all integers or all floats).

Characteristics of Arrays

  • No fixed size: Can be dynamically expanded or shrunk.
  • Allows operations such as:
    • append(): To add values.
    • index(): To find the index of a particular value.

Using Arrays in Python

  1. Importing the Array Module:

    • Use import array to access array functionalities.
    • Alternatively, import array as a for shorthand usage (e.g., a.array()).
    • Specific functions can also be imported using from array import *.
  2. Creating an Array:

    • Syntax: array(typecode, [values])
    • Example for integer array:
      import array  
      vals = array('i', [5, 9, 8, 4, 2])  
      
    • Typecodes:
      • i: signed int
      • I: unsigned int
      • f: float
      • d: double float
      • u: Unicode characters

Working with Array Elements

  • Accessing Elements:
    • Indexing starts at 0.
    • Example: vals[0] accesses first element.
  • Looping Through Arrays:
    • Using for loops:
      for e in vals:  
          print(e)  
      
    • Length of an array can be found using len(), allowing dynamic ranges.

Operations on Arrays

  • Common Methods:
    • append(): Adds an element.
    • remove(): Removes an element.
    • reverse(): Reverses elements in-place.
    • buffer_info(): Returns address and size of the array.
  • Creating a Copy:
    • Another array can be created with the same values:
      new_vals = array(vals.typecode, [val for val in vals])  
      
  • Power Operation:
    • Example: Assign squares of existing values to another array.

Using While Loops with Arrays

  • While loops can also iterate through arrays with necessary condition checks and manual index increments.
  • Example of while loop for printing:
    i = 0  
    while i < len(new_array):  
        print(new_array[i])  
        i += 1  
    

Conclusion

  • Arrays offer a type-restricted alternative to lists in Python.
  • They support various operations and are flexible in terms of size.
  • Message from Ivan: Feedback and engagement appreciated through comments and likes.

Additional Notes

  • Arrays are most useful in scenarios where all elements need to be of the same data type for consistency and efficiency purposes.