Что такое array в python
Перейти к содержимому

Что такое array в python

  • автор:

array — Efficient arrays of numeric values¶

This module defines an object type which can compactly represent an array of basic values: characters, integers, floating point numbers. Arrays are sequence types and behave very much like lists, except that the type of objects stored in them is constrained. The type is specified at object creation time by using a type code, which is a single character. The following type codes are defined:

Minimum size in bytes

signed long long

unsigned long long

It can be 16 bits or 32 bits depending on the platform.

Changed in version 3.9: array(‘u’) now uses wchar_t as C type instead of deprecated Py_UNICODE . This change doesn’t affect its behavior because Py_UNICODE is alias of wchar_t since Python 3.3.

Deprecated since version 3.3, will be removed in version 4.0.

The actual representation of values is determined by the machine architecture (strictly speaking, by the C implementation). The actual size can be accessed through the array.itemsize attribute.

The module defines the following item:

A string with all available type codes.

The module defines the following type:

class array. array ( typecode [ , initializer ] ) ¶

A new array whose items are restricted by typecode, and initialized from the optional initializer value, which must be a list, a bytes-like object , or iterable over elements of the appropriate type.

If given a list or string, the initializer is passed to the new array’s fromlist() , frombytes() , or fromunicode() method (see below) to add initial items to the array. Otherwise, the iterable initializer is passed to the extend() method.

Array objects support the ordinary sequence operations of indexing, slicing, concatenation, and multiplication. When using slice assignment, the assigned value must be an array object with the same type code; in all other cases, TypeError is raised. Array objects also implement the buffer interface, and may be used wherever bytes-like objects are supported.

Raises an auditing event array.__new__ with arguments typecode , initializer .

The typecode character used to create the array.

The length in bytes of one array item in the internal representation.

Append a new item with value x to the end of the array.

Return a tuple (address, length) giving the current memory address and the length in elements of the buffer used to hold array’s contents. The size of the memory buffer in bytes can be computed as array.buffer_info()[1] * array.itemsize . This is occasionally useful when working with low-level (and inherently unsafe) I/O interfaces that require memory addresses, such as certain ioctl() operations. The returned numbers are valid as long as the array exists and no length-changing operations are applied to it.

When using array objects from code written in C or C++ (the only way to effectively make use of this information), it makes more sense to use the buffer interface supported by array objects. This method is maintained for backward compatibility and should be avoided in new code. The buffer interface is documented in Buffer Protocol .

“Byteswap” all items of the array. This is only supported for values which are 1, 2, 4, or 8 bytes in size; for other types of values, RuntimeError is raised. It is useful when reading data from a file written on a machine with a different byte order.

Return the number of occurrences of x in the array.

Append items from iterable to the end of the array. If iterable is another array, it must have exactly the same type code; if not, TypeError will be raised. If iterable is not an array, it must be iterable and its elements must be the right type to be appended to the array.

Appends items from the string, interpreting the string as an array of machine values (as if it had been read from a file using the fromfile() method).

New in version 3.2: fromstring() is renamed to frombytes() for clarity.

Read n items (as machine values) from the file object f and append them to the end of the array. If less than n items are available, EOFError is raised, but the items that were available are still inserted into the array.

Append items from the list. This is equivalent to for x in list: a.append(x) except that if there is a type error, the array is unchanged.

Extends this array with data from the given unicode string. The array must be a type ‘u’ array; otherwise a ValueError is raised. Use array.frombytes(unicodestring.encode(enc)) to append Unicode data to an array of some other type.

Return the smallest i such that i is the index of the first occurrence of x in the array. The optional arguments start and stop can be specified to search for x within a subsection of the array. Raise ValueError if x is not found.

Changed in version 3.10: Added optional start and stop parameters.

Insert a new item with value x in the array before position i. Negative values are treated as being relative to the end of the array.

Removes the item with the index i from the array and returns it. The optional argument defaults to -1 , so that by default the last item is removed and returned.

Remove the first occurrence of x from the array.

Reverse the order of the items in the array.

Convert the array to an array of machine values and return the bytes representation (the same sequence of bytes that would be written to a file by the tofile() method.)

New in version 3.2: tostring() is renamed to tobytes() for clarity.

Write all items (as machine values) to the file object f.

Convert the array to an ordinary list with the same items.

Convert the array to a unicode string. The array must be a type ‘u’ array; otherwise a ValueError is raised. Use array.tobytes().decode(enc) to obtain a unicode string from an array of some other type.

When an array object is printed or converted to a string, it is represented as array(typecode, initializer) . The initializer is omitted if the array is empty, otherwise it is a string if the typecode is ‘u’ , otherwise it is a list of numbers. The string is guaranteed to be able to be converted back to an array with the same type and value using eval() , so long as the array class has been imported using from array import array . Examples:

Packing and unpacking of heterogeneous binary data.

Packing and unpacking of External Data Representation (XDR) data as used in some remote procedure call systems.

8.7. array — Efficient arrays of numeric values¶

This module defines an object type which can compactly represent an array of basic values: characters, integers, floating point numbers. Arrays are sequence types and behave very much like lists, except that the type of objects stored in them is constrained. The type is specified at object creation time by using a type code, which is a single character. The following type codes are defined:

Type code C Type Python Type Minimum size in bytes Notes
‘b’ signed char int 1  
‘B’ unsigned char int 1  
‘u’ Py_UNICODE Unicode character 2 (1)
‘h’ signed short int 2  
‘H’ unsigned short int 2  
‘i’ signed int int 2  
‘I’ unsigned int int 2  
‘l’ signed long int 4  
‘L’ unsigned long int 4  
‘q’ signed long long int 8 (2)
‘Q’ unsigned long long int 8 (2)
‘f’ float float 4  
‘d’ double float 8  

The ‘u’ type code corresponds to Python’s obsolete unicode character ( Py_UNICODE which is wchar_t ). Depending on the platform, it can be 16 bits or 32 bits.

‘u’ will be removed together with the rest of the Py_UNICODE API.

Deprecated since version 3.3, will be removed in version 4.0.

The ‘q’ and ‘Q’ type codes are available only if the platform C compiler used to build Python supports C long long , or, on Windows, __int64 .

New in version 3.3.

The actual representation of values is determined by the machine architecture (strictly speaking, by the C implementation). The actual size can be accessed through the itemsize attribute.

The module defines the following type:

class array. array ( typecode [ , initializer ] ) ¶

A new array whose items are restricted by typecode, and initialized from the optional initializer value, which must be a list, a bytes-like object , or iterable over elements of the appropriate type.

If given a list or string, the initializer is passed to the new array’s fromlist() , frombytes() , or fromunicode() method (see below) to add initial items to the array. Otherwise, the iterable initializer is passed to the extend() method.

A string with all available type codes.

Array objects support the ordinary sequence operations of indexing, slicing, concatenation, and multiplication. When using slice assignment, the assigned value must be an array object with the same type code; in all other cases, TypeError is raised. Array objects also implement the buffer interface, and may be used wherever bytes-like objects are supported.

The following data items and methods are also supported:

The typecode character used to create the array.

The length in bytes of one array item in the internal representation.

Append a new item with value x to the end of the array.

Return a tuple (address, length) giving the current memory address and the length in elements of the buffer used to hold array’s contents. The size of the memory buffer in bytes can be computed as array.buffer_info()[1] * array.itemsize . This is occasionally useful when working with low-level (and inherently unsafe) I/O interfaces that require memory addresses, such as certain ioctl() operations. The returned numbers are valid as long as the array exists and no length-changing operations are applied to it.

When using array objects from code written in C or C++ (the only way to effectively make use of this information), it makes more sense to use the buffer interface supported by array objects. This method is maintained for backward compatibility and should be avoided in new code. The buffer interface is documented in Buffer Protocol .

“Byteswap” all items of the array. This is only supported for values which are 1, 2, 4, or 8 bytes in size; for other types of values, RuntimeError is raised. It is useful when reading data from a file written on a machine with a different byte order.

Return the number of occurrences of x in the array.

array. extend ( iterable ) ¶

Append items from iterable to the end of the array. If iterable is another array, it must have exactly the same type code; if not, TypeError will be raised. If iterable is not an array, it must be iterable and its elements must be the right type to be appended to the array.

array. frombytes ( s ) ¶

Appends items from the string, interpreting the string as an array of machine values (as if it had been read from a file using the fromfile() method).

New in version 3.2: fromstring() is renamed to frombytes() for clarity.

Read n items (as machine values) from the file object f and append them to the end of the array. If less than n items are available, EOFError is raised, but the items that were available are still inserted into the array. f must be a real built-in file object; something else with a read() method won’t do.

array. fromlist ( list ) ¶

Append items from the list. This is equivalent to for x in list: a.append(x) except that if there is a type error, the array is unchanged.

Deprecated alias for frombytes() .

array. fromunicode ( s ) ¶

Extends this array with data from the given unicode string. The array must be a type ‘u’ array; otherwise a ValueError is raised. Use array.frombytes(unicodestring.encode(enc)) to append Unicode data to an array of some other type.

Return the smallest i such that i is the index of the first occurrence of x in the array.

Insert a new item with value x in the array before position i. Negative values are treated as being relative to the end of the array.

Removes the item with the index i from the array and returns it. The optional argument defaults to -1 , so that by default the last item is removed and returned.

Remove the first occurrence of x from the array.

Reverse the order of the items in the array.

Convert the array to an array of machine values and return the bytes representation (the same sequence of bytes that would be written to a file by the tofile() method.)

New in version 3.2: tostring() is renamed to tobytes() for clarity.

Write all items (as machine values) to the file object f.

Convert the array to an ordinary list with the same items.

Deprecated alias for tobytes() .

Convert the array to a unicode string. The array must be a type ‘u’ array; otherwise a ValueError is raised. Use array.tobytes().decode(enc) to obtain a unicode string from an array of some other type.

When an array object is printed or converted to a string, it is represented as array(typecode, initializer) . The initializer is omitted if the array is empty, otherwise it is a string if the typecode is ‘u’ , otherwise it is a list of numbers. The string is guaranteed to be able to be converted back to an array with the same type and value using eval() , so long as the array class has been imported using from array import array . Examples:

Learn How To Use Arrays In Python With Example

Edureka

In the immensely fast moving world, one needs resourceful coding techniques that could help the programmer to sum up voluminous codes in the simplest and most convenient ways. Arrays are one of the data structures that help you write a number of values into a single variable, thereby reducing the burden of memorizing an enormous number of variables. So let’s go ahead, and see how you can implement Arrays in Python.

Here’s an overview of the topics which explains all the aspects dealing with arrays:

  1. Why use Arrays in Python?
  2. What is an Array?
  3. Is Python list same as an Array?
  4. Creating an Array
  5. Accessing an Element
  6. Basic Array Operations
  • Adding/ Changing elements of an Array
  • Concatenation
  • Deleting / Removing elements from an Array
  • Looping through an array
  • Slicing

Why use Arrays in Python?

A combination of Arrays, together with Python could save you a lot of time. As mentioned earlier, arrays help you reduce the overall size of your code, while Python helps you get rid of problematic syntax, unlike other languages. For example: If you had to store integers from 1–100, you won’t be able to remember 100 variable names explicitly, therefore, you can save them easily using an array.

Now that you are aware of the importance of arrays in Python, let’s study more about it in detail.

What is an Array?

An array is basically a data structure which can hold more than one value at a time. It is a collection or ordered series of elements of the same type.

We can loop through the array items easily and fetch the required values by just specifying the index number. Arrays are mutable(changeable) as well, therefore, you can perform various manipulations as required.

Now, there is always a question that comes up to our mind —

Is Python list same as an Array?

The ‘array’ data structure in core python is not very efficient or reliable. Therefore, when we talk about python arrays, we usually mean python lists.

However, python does provide Numpy Arrays which are a grid of values used in Data Science.

Creating an Array:

Arrays in Python can be created after importing the array module as follows —

→ import array as arr

The array(data type, value list) function takes two parameters, the first being the data type of the value to be stored and the second is the value list. The data type can be anything such as int, float, double, etc. Please make a note that arr is the alias name and is for ease of use. You can import without alias as well. There is another way to import the array module which is —

→ from array import *

This means you want to import all functions from the array module.

The following syntax is used to create an array.

Syntax:

Example: a=arr.array( ‘d’ , [1.1 , 2.1 ,3.1] )

Here, the first parameter is ‘d’ which is a data type i.e. float and the values are specified as the next parameter.

Note: All values specified are of the type float. We cannot specify the values of different data types to a single array.

The following table shows you the various data types and their codes.

Accessing array elements :

To access array elements, you need to specify the index values. Indexing starts at 0 and not from 1. Hence, the index number is always 1 less than the length of the array.

Syntax:

Output:

The output returned is the value, present in the second place in our array which is 2.1.

Let us have a look at some of the basic array operations now.

Basic array operations :

There are many operations that can be performed on arrays which are as follows —

Finding the Length of an Array

Length of an array is the number of elements that are actually present in an array. You can make use of len() function to achieve this. The len() function returns an integer value that is equal to the number of elements present in that array.

Syntax:

Example:

Output:

This returns a value of 3 which is equal to the number of array elements.

Adding/ Changing elements of an Array:

We can add value to an array by using the append(), extend() and the insert (i,x) functions.

The append() function is used when we need to add a single element at the end of the array.

Example:

Output

The resultant array is the actual array with the new value added at the end of it. To add more than one element, you can use the extend() function. This function takes a list of elements as its parameter. The contents of this list are the elements to be added to the array.

Example:

Output

The resulting array will contain all the 3 new elements added to the end of the array.

However, when you need to add a specific element at a particular position in the array, the insert(i,x) function can be used. This function inserts the element at the respective index in the array. It takes 2 parameters where the first parameter is the index where the element needs to be inserted and the second is the value.

Example:

Output

The resulting array contains the value 3.8 at the 3rd position in the array.

Arrays can be merged as well by performing array concatenation.

Array Concatenation :

Any two arrays can be concatenated using the + symbol.

Example:

Output —

The resulting array c contains concatenated elements of arrays a and b.

Now, let us see how you can remove or delete items from an array.

Removing/ Deleting elements of an array:

Array elements can be removed using pop() or remove() method. The difference between these two functions is that the former returns the deleted value whereas the latter does not.

The pop() function takes either no parameter or the index value as its parameter. When no parameter is given, this function pops() the last element and returns it. When you explicitly supply the index value, the pop() function pops the required elements and returns it.

Example:

Output —

The first pop() function removes the last value 4.6 and returns the same while the second one pops the value at the 4th position which is 3.1 and returns the same.

The remove() function, on the other hand, is used to remove the value where we do not need the removed value to be returned. This function takes the element value itself as the parameter. If you give the index value in the parameter slot, it will throw an error.

Example:

Output —

The output is an array containing all elements except 1.1.

When you want a specific range of values from an array, you can slice the array to return the same, as follows.

Slicing an array :

An array can be sliced using the : symbol. This returns a range of elements that we have specified by the index numbers.

Example:

Output

The result will be elements present at 1st, 2nd and 3rd position in the array.

Looping through an array:

Using the for loop, we can loop through an array.

Example:

Output

The above output shows the result using for loop. When we use for loop without any specific parameters, the result contains all the elements of the array given one at a time. In the second for loop, the result contains only the elements that are specified using the index values. Please note that the result does not contain the value at index number 3.

Hope you are clear with all that has been shared with you in this tutorial. This brings us to the end of our article on Arrays in Python. Make sure you practice as much as possible and revert your experience.

If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to Edureka’s official site.

Do look out for other articles in this series which will explain the various other aspects of Python and Data Science.

Introduction to Python:
Arrays

An array (aka a matrix) is an efficient way to handle multiple numbers. Importantly, it is more efficient than using a list. It is available from the Numpy package.

1 Create an Array

An array is created manually by first creating a list (or a list-of-list) of numbers and then using the array() function to convert it:

To create an array of all ones for a given size:

…and all zeroes for a given size:

2 Index an Array

Indexing is done with square brackets. Remember that Python uses zero-indexing, meaning that the first element is at index 0, the second is at index 1 and so on. This means that the number at index 4 of the list/array [10, 20, 30, 40, 50, 60, 70] is “50”:

Use the enumerate() function to iterate over both the values in an array and their indexes. This can be used, for example, to find the index of the first value in an array to meet a certain condition. In the below example, the first occurrence of the number “4” is searched for using the next() function and it is found at index 3 in the array:

For the record, the actual value (as opposed to the index) can be returned in a similar fashion:

Sort an array into numerical order and find the index where, if you were to insert a given number, it would maintain the numerical order:

3 Augment an Array

3.1 Append

Add to an array using Numpy’s append() function. You can append a single element, an array of elements or a list of them:

3.2 Concatenate

To append elements as a new row you need to use the concatenate() function, although this can be a bit confusing. If you simply concatenate two arrays it will act identically to the append() function (although note that you need to use an extra set of round brackets when specifying the arrays to concatenate):

The reason you need to use two sets of round brackets is because there is a hidden keyword argument included in the concatenate() function called “ axis ”. If we leave it out (as we did in the previous example) it will take the default value of None and as a result it will flatten the arrays before concatenating them. This is why the functionality of the above example was identical to the append() function. Here is the example again but with the axis keyword argument explicitly shown:

As you can see, the above example is identical to the one before it, and both are identical to using the append() function.

If we want to take control of the behaviour we need to specify which axis to concatenate along, either the “0” axis or the “1” axis. In our previous examples, our arrays have only had one dimension each and with one-dimensional data we only have the option to concatenate along the 0th axis:

If we changed the above to axis=1 the script would fail because it would be looking for an extra dimension to the data which doesn’t exist. If we instead used two-dimensional data (ie arrays made from lists-of-lists) we could do the following:

Note that axis=0 doesn’t consistently mean “concatenate horizontally” or “concatenate vertically”. It means “concatenate along the highest dimension”. This means that, for this data, axis=1 will concatenate horizontally and we will yet again produce 1 2 3 4 5 6 as an output (although this time it will be two-dimensional data — although only one dimension is occupied — as shown by the double square brackets in the output):

If you recall our first concatenate() example you’ll remember that not specifying an axis (or, equivalently, specifying it as None ) it will flatten the arrays before concatenating, resulting in one-dimensional data (note the single square brackets in the output):

Finally, here is a way to do a ‘line-break’: convert a one-dimensional array into a two-dimensional one:

3.3 Transpose

Flipping an array along a diagonal axis can be done with the .T method:

The .transpose() method also works:

Here’s how to use transposition to concatenate arrays in the exact way you want:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *