hi everybody..... i'm using an array to make a program but i'm not able to find the size (length) of the array.can anyone tell me how to do this?

Dani AI

Generated

As noted, the right answer depends on what you mean by "array" — different containers expose different metadata. The short version: built‑in sequences give you the length of the outer container, numeric array libraries store shape/metadata, and generators/iterators don’t expose a length at all. Here are a few practical points and small snippets that fill gaps users often run into.

For NumPy ndarrays you can ask the array for more than just its dimensions — there are attributes that tell you the total element count, how many axes it has, and how many bytes the data buffer consumes:

# given a NumPy ndarray 'a'
a.size     # total number of elements
a.ndim     # number of dimensions (axes)
a.nbytes   # bytes used by the underlying data buffer

For Python lists a single length call reports the outer list only. If you have a 2D list and want the grand total of inner elements, flattening or summing inner lengths works. Example using itertools and a small recursive alternative for irregular nesting:

from itertools import chain
total = sum(1 for _ in chain.from_iterable(matrix))

def deep_count(seq):
    return sum(deep_count(x) if isinstance(x, list) else 1 for x in seq)

Quick tips: len-like queries on dicts count keys; generators need to be consumed to count items (so be careful with memory); sys.getsizeof shows object overhead, not deep memory use; NumPy attributes are O(1) (metadata), whereas flattening or iterating to count is O(n). If you’re doing numeric work at scale, converting data to NumPy early makes shape/size queries and bulk operations simpler and much faster.

Recommended Answers

All 2 Replies

If you mean an array in the numpy sense. e.g., z = numpy.zeros([5,3],float) then the shape attribute is what you want, e.g. z.shape returns (5,3).

If you're implementing an array as a Python list, then len(z) is what you want.

commented: nice help +7

thanks you very much.its what i wanted.....

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.