473,703 Members | 3,037 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 53021
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
2081
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
1858
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
1760
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
8363
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
15594
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
2100
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
6606
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
1402
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
29295
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
8759
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
9122
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...
0
8963
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7872
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...
1
6588
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5922
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4433
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4687
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2453
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.