473,665 Members | 2,740 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to test if object is sequence, or iterable?

Hi,

I'd like to know if there's a way to check if an object is a sequence,
or an iterable. Something like issequence() or isiterable().

Does something like that exist? (Something which, in case of iterable,
doesn't consume the first element of the iterable)

Regards,

--Tim

Jul 22 '06 #1
7 53011
Tim N. van der Leeuw a écrit :
Hi,

I'd like to know if there's a way to check if an object is a sequence,
or an iterable. Something like issequence() or isiterable().

Does something like that exist? (Something which, in case of iterable,
doesn't consume the first element of the iterable)
isiterable = lambda obj: isinstance(obj, basestring) \
or getattr(obj, '__iter__', False)
Should cover most cases.
Jul 22 '06 #2

Bruno Desthuilliers wrote:
Tim N. van der Leeuw a écrit :
Hi,

I'd like to know if there's a way to check if an object is a sequence,
or an iterable. Something like issequence() or isiterable().

Does something like that exist? (Something which, in case of iterable,
doesn't consume the first element of the iterable)

isiterable = lambda obj: isinstance(obj, basestring) \
or getattr(obj, '__iter__', False)
Should cover most cases.
Yes, that seems to cover all cases I can think of, indeed. Funny
though, that string objects do not have an '__iter__' method, but are
still iterable... But it will make most of my use-cases easier: Often I
want to iterate over something, if it's an iterable, except when it's a
string.
Thanks,

--Tim

Jul 22 '06 #3

"Tim N. van der Leeuw" <ti************ *@nl.unisys.com wrote in message
news:11******** **************@ h48g2000cwc.goo glegroups.com.. .
Hi,

I'd like to know if there's a way to check if an object is a sequence,
or an iterable. Something like issequence() or isiterable().
How about
try: it = iter(possible_i terable)
except TypeError: bail()

Terry Jan Reedy

Jul 22 '06 #4
In <44************ ***********@new s.free.fr>, Bruno Desthuilliers wrote:
Tim N. van der Leeuw a écrit :
>Hi,

I'd like to know if there's a way to check if an object is a sequence,
or an iterable. Something like issequence() or isiterable().

Does something like that exist? (Something which, in case of iterable,
doesn't consume the first element of the iterable)

isiterable = lambda obj: isinstance(obj, basestring) \
or getattr(obj, '__iter__', False)
Should cover most cases.
What about objects that just implement an apropriate `__getitem__()`
method?

Ciao,
Marc 'BlackJack' Rintsch
Jul 22 '06 #5
Marc 'BlackJack' Rintsch a écrit :
In <44************ ***********@new s.free.fr>, Bruno Desthuilliers wrote:

>>Tim N. van der Leeuw a écrit :
>>>Hi,

I'd like to know if there's a way to check if an object is a sequence,
or an iterable. Something like issequence() or isiterable().

Does something like that exist? (Something which, in case of iterable,
doesn't consume the first element of the iterable)

isiterable = lambda obj: isinstance(obj, basestring) \
or getattr(obj, '__iter__', False)
Should cover most cases.


What about objects that just implement an apropriate `__getitem__()`
method?
Hmmm... (quick test)

Good point.

FWIW, Terry's solution might be far better.
Jul 22 '06 #6
Tim,

An object is iterable if it implements the iterator protocol. A good
enough check to see if it does is to check for the presense of the
__iter__() method. The way to do it is:
hasattr(object, '__iter__')

You are correct in the fact that you check if an object is iterable
rather than using isinstance to check if it is of a partucular type.
You are doing things 'the pythonic way' ;)

Nick Vatamaniuc
Tim N. van der Leeuw wrote:
Hi,

I'd like to know if there's a way to check if an object is a sequence,
or an iterable. Something like issequence() or isiterable().

Does something like that exist? (Something which, in case of iterable,
doesn't consume the first element of the iterable)

Regards,

--Tim
Jul 22 '06 #7

"Nick Vatamaniuc" <va******@gmail .comwrote in message
news:11******** *************@h 48g2000cwc.goog legroups.com...
Tim,

An object is iterable if it implements the iterator protocol
There are presently two iterator protocols. The old one will be likely be
dropped in 3.0 (currently being discussed).
>. A good
enough check to see if it does is to check for the presense of the
__iter__() method. The way to do it is:
hasattr(object, '__iter__')
Sorry, this check for the newer and nicer protocol but not the older one.
>>hasattr('abc' , '__iter__')
False

This may change in 2.6. The defacto *version-independent* way to determine
iterability is to call iter(ob). If it returns an iterator, you can
iterate; if it raises TypeError, you cannot. Any it should be patched as
necessary by the developers to continue doing the right thing in future
versions.

Terry Jan Reedy

Jul 23 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
2077
by: Leif K-Brooks | last post by:
Is there a word for an iterable object which isn't also an iterator, and therefor can be iterated over multiple times without being exhausted? "Sequence" is close, but a non-iterator iterable could technically provide an __iter__ method without implementing the sequence protocol, so it's not quite right.
18
1857
by: alex | last post by:
Hi there, how can I check if a variable is a structure (i.e. a list)? For my special problem the variable is either a character string OR a list of character strings line So how can I test if a variable 'a' is either a single character string or a list? I tried: if a is list:
1
1759
by: Daniel Poetzinger | last post by:
Hello List Sorry if this question is too simple or unreleated, but I didn't found an answer yet: How is it possible to handle an element: <test>1 2 3 4</test> as sequence of atomic types (xs:integer) in an XQuery? A cast to xs:integer* is not possible I think...
176
8336
by: nw | last post by:
Hi, I previously asked for suggestions on teaching testing in C++. Based on some of the replies I received I decided that best way to proceed would be to teach the students how they might write their own unit test framework, and then in a lab session see if I can get them to write their own. To give them an example I've created the following UTF class (with a simple test program following). I would welcome and suggestions on how anybody...
5
15591
by: tom | last post by:
Hi! My code is And it gives following error: How can sortedList variable turn into NoneType? I just don't get it...
0
2092
by: Mikelowe | last post by:
Would like to know is there an automated way to copy the maxvalue of sequence number from db2 production to db2 test. When we copy data from our production that uses a sequence number value as its unique key into test, we get problems doing inserts in test unless we also manually update the test.sequence to be equal to or greater than the production.sequence number. Can this manual process be automated by a utility or something simple? ...
5
6605
by: Anan18 | last post by:
Hello sir, I'm supposed to Implement and Test the sequence Class Using a Fixed-Sized Array (Chapter 3), from Data Structures & Other objects using c++. The header file is provided, and so is a test program to check the correctness of the sequence class. I cannot figure out what the problem is and keep looking back and forth at the textbook and its not helping, can someone please please help me , i cannot figure out the errors in the...
11
1398
by: Erich | last post by:
Hello all, Today I found myself once again defining two functions that I use all the time: nsplit and iterable. These little helper functions of mine get used all the time when I work. Im sick of having to define them (but am very good at it these days, less than 1 typo per function!). It leads me to the following questions 1. Is this functionality already built in and im just missing it 2. Is there some well known, good technique...
3
29292
by: william hoskins | last post by:
Hey everyone, I am fairly new to python, and I was working on a google app engine project for a class, and this error came up. I wasn't sure why, because right above it I have the same object type right above it, and when I take the filter off the other, it works fine, I just can't do that or it screws everything up def LoginBar(): user = users.get_current_user() greet = Greeting.all() info = greet greet.filter("username...
0
8438
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8348
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8863
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8779
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8549
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7376
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4356
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2004
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1761
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.