Computer Science

Python Array Operations

Python array operations involve manipulating arrays, which are data structures that store elements of the same type. Common array operations in Python include accessing elements by index, slicing, adding or removing elements, and performing mathematical operations on arrays. These operations are essential for working with large sets of data and implementing algorithms in Python.

Written by Perlego with AI-assistance

5 Key excerpts on "Python Array Operations"

  • Book cover image for: Fundamentals of Python
    eBook - PDF

    Fundamentals of Python

    Data Structures

    This chapter examines the data organization and concrete details of processing that are particular to arrays and linked structures. Their use in implementing various types of collections is discussed in later chapters. The Array Data Structure An array represents a sequence of items that can be accessed or replaced at given index positions. You are probably thinking that this description resembles that of a Python list. In fact, the data structure underlying a Python list is an array. Although Python programmers would typically use a list where you might use an array, the array rather than the list is the primary implementing structure in the collections of Python and many other programming languages. Therefore, you need to become familiar with the array way of thinking. Some of what this chapter has to say about arrays also applies to Python lists, but arrays are much more restrictive. A programmer can access and replace an array’s items at given positions, examine an array’s length, and obtain its string representation—but that’s all. The programmer cannot add or remove positions or make the length of the array larger or smaller. Typically, the length or capacity of an array is fixed when it is created. Python’s array module does include an array class, which behaves more like a list but is limited to storing numbers. For purposes of the discussion that follows, you will define a new class named Array that adheres to the restrictions mentioned earlier but can hold items of any type. Ironically, this Array class uses a Python list to hold its items. The class defines methods that allow clients to use the subscript operator [], the len function, the str function, and the for loop with array objects. The Array methods needed for these operations are listed in Table 4-1. The variable a in the left column refers to an Array object.
  • Book cover image for: Introduction to Computational Models with Python
    Using Arrays with Numpy squaresolid 255 17.6 SUMMARY Arrays are data structures that store collections of data. To refer to an indi-vidual element, an integer value, known as the index, is used to indicate the relative position of the element in the array. Python and Numpy manipulate arrays as vectors and matrices. Many operations and functions are defined for creating and manipulating vectors and matrices. Key Terms arrays elements index vectors array elements matrices column vector row vector two-dimensional array vector operations vector functions complex vectors 17.7 EXERCISES 17.1 Develop a Python program that computes the values in a vector V that are the sines of the elements of vector T . The program must assign to T a vector with 75 elements running from 0 to 2 π . Plot the elements of V as a function of the elements of T ; use GnuPlot or matplotlib . 17.2 Develop a Python program that finds the index of the first negative number in a vector. If there are no negative numbers, it should set the result to − 1. 17.3 The Fibonacci series is defined by F n = F n − 1 + F n − 2 . Develop a Python program that computes a vector with the first n elements of a Fibonacci series. A second vector should also be computed with the ratios of con-secutive Fibonacci numbers. The program must plot this second vector using GnuPlot or matplotlib . 17.4 Develop a Python program that reads the values of a vector P and com-putes the element values of vector Q with the cubes of the positive values in vector P . For every element in P that is negative, the corresponding element in Q should be set to zero. 17.5 Develop a Python program that reads the values of a vector P and assigns the element values of vector Q with every other element in vector P . 17.6 Develop a Python program that reads the values of a matrix M of m rows and n columns. The program must create a column vector for every column in matrix M , and a row vector for every row in matrix M .
  • Book cover image for: NCV2 Basic Principles of Computer Programming and Computer Literacy
    280 Module 11 Arrays and lists Introduction Computers process and store data accurately and at an exceptionally high speed. It is also essential that the stored data can be accessed quickly. There are different ways of achieving accuracy and speed, such as the implementation of text files, databases and data structures. In this module, you are going to learn more about data structures specific to Python. 11.1 One-dimensional arrays and basic lists 11.1.1 Define data structure Data structures are a way of organising and storing data in a computer system so that it can be accessed more efficiently depending on the situation. Programming languages are built around data structures. Compared to other programming languages, Python simplifies the learning of these data structures, as you will discover as you work your way through this module. VOCABULARY Data structure – specialised means of organising, processing, retrieving and storing data General data structures In Python, data structures are implicitly supported, which enables you to store and access data easily. Under built-in data structures, the following are included: list, dictionary, tuple, array and set. NOTE Python does not have a built-in concept of the array, but you can import it using the array module or the NumPy library. NumPy stands for Numerical Python and is a Python library used for working with arrays. The distinction will be explained a little later. In Python, users can also create their own data structures, enabling them to customise their functionality. Stacks, queues, trees, linked lists, and so forth, all of which are available to users in other programming languages, fall under the category of user-defined structures. In this module, we are going to focus on lists, arrays and dictionaries in detail.
  • Book cover image for: Introduction to Engineering and Scientific Computing with Python
    • David E. Clough, Steven C. Chapra(Authors)
    • 2022(Publication Date)
    • CRC Press
      (Publisher)
    ndarray class of the NumPy module come into play. These arrays are the focus of this chapter.
    What are typical computational tasks that involve arrays? Here are several examples:
    • storing and accessing tables of data, such as those that describe physical or chemical properties of substances, alloys, composites, or mixtures,
    • collections of measurements from experiments, manufacturing processes, or environmental phenomena,
    • discrete approximations of continuous quantities, such as temperatures throughout a solid object like a cooling fin,
    • case studies where input parameters are varied over a range of interest, and output results are computed and displayed in plots, and
    • physical or chemical variables that occur in staged processes, such as those used to separate desired products from waste or materials to be recycled.
    To proceed, we need to know how to create arrays, either in one or two dimensions. Next, we must know how to include arrays in numerical calculations, often called array operations. Then, we move on to vector/matrix calculations including multiplication and transpose. Finally, we introduce the linalg module which contains many useful functions for array and matrix calculations.
    A caution to the student. This chapter introduces many concepts and methods that are likely to be new to you. To make the presentation complete, we introduce alternate methods to accomplish certain computations. You will have the opportunity to select methods with which you are most comfortable, and your instructor may have preferences. Also, after the introduction provided in this chapter, you will see the methods repeated in subsequent chapters, and, in that way, you will be able to become better oriented to them. We have two suggestions as you study this chapter. First, work through everything carefully, replicating all the example code, and trying variations. Second, be patient and do not get too discouraged if you encounter difficulties.
  • Book cover image for: Numerical Methods in Engineering with Python 3
    Recall that Python se- quences have zero offset, so that a[0] represents the first row, a[1] the second row, etc. With very few exceptions we do not use lists for numerical arrays. It is much more convenient to employ array objects provided by the numpy module. Array objects are discussed later. Arithmetic Operators Python supports the usual arithmetic operators: + Addition − Subtraction ∗ Multiplication / Division ∗∗ Exponentiation % Modular division Some of these operators are also defined for strings and sequences as follows: >>> s = ’Hello ’ >>> t = ’to you’ 7 1.2 Core Python >>> a = [1, 2, 3] >>> print(3*s) # Repetition Hello Hello Hello >>> print(3*a) # Repetition [1, 2, 3, 1, 2, 3, 1, 2, 3] >>> print(a + [4, 5]) # Append elements [1, 2, 3, 4, 5] >>> print(s + t) # Concatenation Hello to you >>> print(3 + s) # This addition makes no sense Traceback (most recent call last): File "", line 1, in print(3 + s) TypeError: unsupported operand type(s) for +: ’int’ and ’str’ Python also has augmented assignment operators, such as a + = b, that are famil- iar to the users of C. The augmented operators and the equivalent arithmetic expres- sions are shown in following table. a += b a = a + b a -= b a = a - b a *= b a = a*b a /= b a = a/b a **= b a = a**b a %= b a = a%b Comparison Operators The comparison (relational) operators return True or False. These operators are < Less than > Greater than <= Less than or equal to >= Greater than or equal to == Equal to != Not equal to Numbers of different type (integer, floating point, and so on) are converted to a common type before the comparison is made. Otherwise, objects of different type are considered to be unequal. Here are a few examples: >>> a = 2 # Integer >>> b = 1.99 # Floating point >>> c = ’2’ # String >>> print(a > b) True
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.