chefhose
chefhose

Reputation: 2694

Function that is agnostic to object implementing len() or shape

I have a function func(x) which expects a parameter x. x should be some kind of collection or array. func(x) needs to get the length of x:

 def func(x):        
    for i in range(len(x)):
        print('Something', i)

The problem is that some collection-like objects have len() implemented but not .shape (e.g. a list) others have .shape implemented but not len() (e.g. a sparse matrix). What is the most pythonic way to make func(x) work, regardless of this issue? Or are there other things to consider when looking for a solution for this problem?

What I can think of:

Upvotes: 2

Views: 106

Answers (1)

Alain T.
Alain T.

Reputation: 42133

The most Pythonic way to approach would be to build the internal logic using iterators rather than indexes.

def func(x):        
    for value in x:
        print('Something', value)

Upvotes: 1

Related Questions