Python iterable object | Lists, tuples, dictionaries, and sets

Python iterable objects are capable of returning its members one at a time, permitting it to be iterated over in a for-loop.

Examples of iterables include all sequence types (such as list, str, and tuple) and some non-sequence types like dict, file objects, and objects of any classes you define with an __iter__() or __getitem__() method.

Remember:-

  • Sequence: Sequence is the collection of data
  • Iterable: Iterable is the sequence type object that supports __iter__ method.

Python iterable object Examples

Lists, tuples, dictionaries, and sets are all iterable objects and have a iter() method which is used to get an iterator:

next() Function

Let’s call the __next__() method using the next() built-in function.

Return an iterator from a tuple, and print each value:

Tuple Example:

Output: John
Amy
Ken

List Example:

Output: Berlin
Vienna
Zurich

Iterating over dictionaries using ‘for’ loops

Output:

x -> 1
y -> 2
z -> 3

Strings Example

Strings are also iterable objects, containing a sequence of characters:

Output:

Python iterable object

How do I add the contents of an iterable to a set?

You can add elements of a list to a set like this:

Output: {0, 1, 2, 3, 4, 5}

Looping Through an Iterator

Python for loop is also best option to iterate through an iterable object:

The for loop actually creates an iterator object and executes the next() method on every loop cycle.

Output: Aki
Boki
Chiku
1
2
3

How to Check an object is iterable or not?

There are many different ways of checking whether an object is iterable or not.

See below simplest examples using iter() function with if else condition statement.

Output:

34 is iterable : False
[4, 5] is iterable : True
EyeHunts is iterable : True

Python iterable type

listtupledictset: construct a list, tuple, dictionary, or set, respectively, from the contents of an iterable.

Do comment if you want to discussion on this topic. We like your input and suggestion.

Note:
IDE: PyCharm 2020.1.1 (Community Edition)
macOS 10.15.4
Python 3.7
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.