Как определить размер массива в python
Перейти к содержимому

Как определить размер массива в 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.

Length of Array in Python

We have learned that arrays are a collection of objects , and these collections can have any number of objects: zero, one, ten, and so on. The number of objects in the array is called its length. We need to know the length of an array to perform various operations like iterating over the array, checking whether an element belongs to the array and reading/updating elements in the array.

Scope

  • In this article , we shall see how the length of an array is calculated in Python using default libraries as well as NumPy library .
  • We will not discuss how these library methods internally work to compute the length of an array in Python programming.

Introduction

Let us take an array as follows:

How many elements are in the array? The answer is 5. Hence the length of the array is also 5.

If we were to give indexes to each element in the array as follows:

Essentially, the length of an array is the highest index position + 1.

Array Length in Python using the len() method

Python has a len() method to find out the length of an array. The syntax is as follows:

Example

Output

Finding the Length of a Python NumPy Array

Numpy is a library compatible with Python for operating complex mathematical operations on multi-dimensional arrays . We use numpy for mathematical operations on arrays. Here is how we can find the length of an array in Python using numpy:

Как найти длину массива в Python

Эй, ребята! Я надеюсь, что у вас все хорошо. В этой статье мы раскрываем 3 варианта длины массива в Python.

  • Автор записи

Как найти длину массива в Python

Эй, ребята! Я надеюсь, что у вас все хорошо. В этой статье мы будем открывать 3 варианта длины массива в Python Отказ

Как мы все знаем, Python не поддерживает или предоставляет нам структуру данных массива прямо. Вместо этого Python обслуживает нас с 3 различными вариантами использования структуры данных массива здесь.

Пойдем сначала пройти различные способы, которыми мы можем создать массив Python.

Кроме того, в предстоящих разделах мы будем обсуждать использование метода Python Len () для получения длины массива в каждом из вариантов.

Нахождение длины массива в Python с использованием метода Len ()

Python предоставляет нам структуру данных массива в формах ниже:

  • Список Python
  • Модуль массива Python

Мы можем создать массив, используя любые из вышеуказанных вариантов и использовать различные функции для работы и манипулирования данными.

Python Len () Метод Позволяет нам найти общее количество элементов в массиве/объекте. То есть он возвращает количество элементов в массиве/объекте.

Давайте теперь понимаем способ узнать длину массива в вышеуказанных вариантах массива Python.

Нахождение длины списка Python

Python Len () Метод Может использоваться со списком для получения и отображения подсчета элементов, занятых списком.

В приведенном ниже примере мы создали список гетерогенных элементов. Кроме того, мы использовали метод Len () для отображения длины списка.

Нахождение длины массива Python

Модуль массива Python Помогает нам создать массив и манипулировать то же самое, используя различные функции модуля. Метод Len () можно использовать для расчета длины массива.

Нахождение длины Python Numpy Array

Как мы все знаем, мы можем создать массив, используя Numpy модуль и использовать его для любой математической цели. Метод Len () помогает нам узнать количество значений данных, присутствующих в Numpy Array.

Заключение

Этим мы дошли до конца этой темы. Не стесняйтесь комментировать ниже, если вы столкнетесь с любым вопросом. До этого, счастливое обучение!

How to calculate the length of an array in Python?

Itexamtools

Arrays make it easy to group values in Python. Keeping these values in one place makes them easy to reference and access at a later point in your code. Arrays thus pave the way for streamlined, manageable code.

This article looks at the different types of arrays in Python and the benefits of each. We’ll then explain how to calculate the length of an array in Python and how we can use array length to alter control flow and determine how much memory an array uses.

What Is an Array?

An array in Python is a group of data points in consecutive memory locations. It’s a special type of variable that contains multiple values that must all be of the same data type. Programmers use arrays to store groups of number values efficiently in code.

Building an Array in Python

There are different ways to build an array in Python. Below we’ll go over lists, arrays, and NumPy arrays.

Lists

What you might know as an array in another language like C++ or Java is actually a list in Python. While it is easy to confuse lists with arrays in Python, a single list can include any number of data types. Lists also do not require the use of a module and can incorporate strings that arrays cannot:

Lists are a convenient way of capturing similar data in one place within code. But Python gives you the ability to create arrays as well.

The Array Module

Python has a module dedicated to arrays in its standard library. The module is conveniently named array , and you'll have to import it to use it. The syntax for adding the array module to your program looks like this:

With the array module imported, you can use this syntax to add an array into your code:

You’re required to list a specific data type for your array upon declaration. All of the array’s values must be of that same data type or your program will return an error. Python uses a series of type codes to identify an array’s data type.

For example, type code ‘i’ is not signed integers, while ‘f’ is for float. See the full list at this Python documentation page.

Your list of values can be any length, from one to theoretical infinity. Below are some examples of arrays you might find in Python:

The NumPy Module

NumPy, or Numerical Python, is a Python module that creates arrays out of lists. This gives NumPy the benefit of using less memory as an array, while being flexible enough to accommodate multiple data types. NumPy also lets programmers perform mathematical calculations that are not possible with standard arrays.

While the array module is one of Python's core libraries, the NumPy module is not. You'll need to install NumPy using the pip3 install numpy command to use it.

Declaring a NumPy array is not much different from declaring a standard array in Python, except there’s no need to list a data type:

Now that we have an understanding of how to create Python’s various arrays, we’ll need to look at the significance of array length.

Using Lists and Arrays in Python

Both lists and arrays help keep code organized by keeping groups of data together in one place. This makes code easier to read and keeps your data concise. Let’s look at each and see when they are most beneficial to use:

Benefits of Lists

While lists are bulkier to store, they allow the convenience of not having to call upon a module and are not limited to one data type. When you have a shorter sequence of values, lists can be the best choice.

Benefits of Arrays

Arrays store each value in subsequent memory locations. Each value in an array is of a specific data type. The program thus knows how much memory to set aside for each. Values in an array tend to be only 2 to 4 bytes versus 64 bytes for each value in a list. This makes arrays much more energy efficient than a list.

Benefits of NumPy Arrays

NumPy is a popular module that is the standard library for scientific computing. NumPy arrays are more compact than lists but also allows for multiple data types in a single array. You can use NumPy for more complex operations such as matrix multiplication. Most deep learning and machine learning libraries build on top of NumPy as well.

How To Calculate the Length of an Array in Python

The length of an array represents the number of elements it contains. When using a list or NumPy array consisting of a string, the length reveals the number of characters in that string. Let’s look at how to calculate array length and ways to use it in your code.

Python makes it easy to calculate the length of any list or array, thanks to the len() method. len() requires only the name of the list or array as an argument. Here's how the len() method looks in code:

It should come as no surprise that this program outputs 8 as the value for counts_length .

You can use the len() method for NumPy arrays, but NumPy also has the built-in typecode . size that you can use to calculate length.

Both outputs return 8, the number of elements in the array.

NumPy is unique in allowing you to capture multi-dimensional arrays. Calling size() on a multi-dimensional array will print out the length of each dimension.

Array Length Use Cases

Array length serves to alter control flow and determine how much memory an array uses.

Altering Control Flow

You can use array length in code to alter control flow. This simple example shows just one potential use for a length value:

Luckily, our array of 8 values meets the minimum length requirement.

Determining How Much Memory an Array Uses

You could also use array length in conjunction with NumPy’s itemsize attribute to tell you the total number of bytes the array uses in memory. Here's an example of what this looks like:

Each integer uses 4 bytes of data for a total of 32 bytes in memory.

Calculating Lengths of Strings

Using len() with a list that makes up a string will reveal the number of characters that make up the string. Strings, just like lists, are a collection of items. Therefore, a string's length is equal to the number of characters within. Take a look at how this works:

We get the following output:

Learn Python at Home With Udacity

This article explored lists, arrays, and NumPy arrays in Python and the benefits of each. We also looked at how to calculate the length of each and how to use this calculation in code.

Want to continue learning all about Python?

Look no further than our Introduction to Programming Nanodegree program. Don’t delay: It’s your first step towards a career in a field like software development, machine learning, or data science!

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

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