Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Check if a list is empty or not in Python
Next article icon

How to check if an object is iterable in Python?

Last Updated : 26 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

In simple words, any object that could be looped over is iterable. For instance, a list object is iterable and so is an str object. The list numbers and string names are iterables because we are able to loop over them (using a for-loop in this case).  In this article, we are going to see how to check if an object is iterable in Python.

Examples: 

Input: “Hello”

Output: object is not iterable

Explanation: Object could be like( h, e, l, l, o)

Input: 5

Output: ‘int’ object is not iterable

Example 1:

Python3




# code
name = "Hello"
 
for letter in name:
  print(letter, end = " ")
 
 

Output:

H e l l o

Example 2:

Python3




# code
number = 5
for i in number:
  print(i)
 
 

Output

TypeError: 'int' object is not iterable

However, an int object is not iterable and so is a float object. The integer object number is not iterable, as we are not able to loop over it.

Checking an object’s iterability in Python

We are going to explore the different ways of checking whether an object is iterable or not. We use the hasattr() function to test whether the string object name has __iter__ attribute for checking iterability. However, this check is not comprehensive.

Method 1: Using __iter__ method check.

Python3




# code
name = 'Roster'
 
if hasattr(name, '__iter__'):
  print(f'{name} is iterable')
   
else:
  print(f'{name} is not iterable')
 
 

Output:

Roster is iterable

Method 2: Using the Iterable class of collections.abc module.

We could verify that an object is iterable by checking whether it is an instance of the Iterable class. The instance check reports the string object as iterable correctly using the Iterable class. This works for Python 3 as well. For Python 3.3 and above, you will have to import the Iterable class from collections.abc and not from collections like so:

Python3




# code
from collections.abc import Iterable
 
name = 'Roster'
 
if isinstance(name, Iterable):
  print(f"{name} is iterable")
   
else:
  print(f"{name} is not iterable")
 
 

Output:

Roster is iterable

Method 3: Using the iter() builtin function.

The iter built-in function works in the following way:

  • Checks whether the object implements __iter__, and calls that to obtain an iterator.
  • If that fails, Python raises TypeError, usually saying “C object is not iterable,” where C is the class of the target object.

Code:

Python3




# code
name = "Roster"
 
try:
  iter(name)
  print("{} is iterable".format(name))
   
except TypeError:
  print("{} is not iterable".format(name))
 
 

Output:

Roster is iterable

Type checking

Here we will check the type of object is iterable or not.

Python3




from collections.abc import Iterable  
 
if isinstance(4, Iterable):
    print("iterable")
else:
    print("not iterable")
 
 

Output:

not iterable


Next Article
Check if a list is empty or not in Python

S

snowflake203
Improve
Article Tags :
  • Python
  • Python collections-module
  • Python-Built-in-functions
  • Technical Scripter 2020
Practice Tags :
  • python

Similar Reads

  • How to Check If Python Package Is Installed
    In this article, we are going to see how to check if Python package is installed or not. Check If Python Package is InstalledThere are various methods to check if Python is installed or not, here we are discussing some generally used methods for Check If Python Package Is Installed or not which are
    5 min read
  • How to Check the Type of an Object in Python
    In this article, we will explore the essential skill of determining the type of an object in Python. Before engaging in any operations on an object within the Python programming language, it is imperative to possess the knowledge of how to check its type. This fundamental task is encountered regular
    4 min read
  • Check if a list is empty or not in Python
    In article we will explore the different ways to check if a list is empty with simple examples. The simplest way to check if a list is empty is by using Python's not operator. Using not operatorThe not operator is the simplest way to see if a list is empty. It returns True if the list is empty and F
    2 min read
  • How to check if a deque is empty in Python?
    In this article, we are going to know how to check if a deque is empty in Python or not. Python collection module provides various types of data structures in Python which include the deque data structure which we used in this article. This data structure can be used as a queue and stack both becaus
    3 min read
  • How to Fix TypeError: 'NoneType' object is not iterable in Python
    Python is a popular and versatile programming language, but like any other language, it can throw errors that can be frustrating to debug. One of the common errors that developers encounter is the "TypeError: 'NoneType' object is not iterable." In this article, we will explore various scenarios wher
    8 min read
  • Check if a List is Sorted or not - Python
    We are given a list of numbers and our task is to check whether the list is sorted in increasing or decreasing order. For example, if the input is [1, 2, 3, 4], the output should be True, but for [3, 1, 2], it should be False. Using all()all() function checks if every pair of consecutive elements in
    3 min read
  • How to Build a basic Iterator in Python?
    Iterators are a fundamental concept in Python, allowing you to traverse through all the elements in a collection, such as lists or tuples. While Python provides built-in iterators, there are times when you might need to create your own custom iterator to handle more complex data structures or operat
    4 min read
  • Check if two lists are identical in Python
    Our task is to check if two lists are identical or not. By "identical", we mean that the lists contain the same elements in the same order. The simplest way to check if two lists are identical using the equality operator (==). Using Equality Operator (==)The easiest way to check if two lists are ide
    2 min read
  • Check If Value Is Int or Float in Python
    In Python, you might want to see if a number is a whole number (integer) or a decimal (float). Python has built-in functions to make this easy. There are simple ones like type() and more advanced ones like isinstance(). In this article, we'll explore different ways to check if a value is an integer
    4 min read
  • Iterate over a set in Python
    The goal is to iterate over a set in Python. Since sets are unordered, the order of elements may vary each time you iterate. You can use a for loop to access and process each element, but the sequence may change with each execution. Let's explore different ways to iterate over a set. Using for loopW
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences