Skip to content

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

  • by

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

Examples of iterable 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() the 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:

mytuple = ("John", "Amy", "Ken")
myit = iter(mytuple)

print(next(myit))
print(next(myit))
print(next(myit))

Output: John
Amy
Ken

List Example:

# list of cities 
cities = ["Berlin", "Vienna", "Zurich"] 
  
# initialize the object 
iterator_obj = iter(cities) 
  
print(next(iterator_obj)) 
print(next(iterator_obj)) 
print(next(iterator_obj))

Output: Berlin
Vienna
Zurich

Iterating over dictionaries using ‘for’ loops

d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
    print(key, '->', d[key])

Output:

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

Strings Example

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

myit = iter('EyeHunts')

print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))

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:

foo = set(range(0, 4))

foo.update(range(2, 6))

print(foo)

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

Looping Through an Iterator

Python for loop is also the 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.

# Tuple
mytuple = ("Aki", "Boki", "Chiku")

for x in mytuple:
    print(x)

# List
myList = [1, 2, 3]

for y in myList:
    print(y)

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.

# Function to check object
# is iterable or not
def iterable(obj):
    try:
        iter(obj)
        return True

    except TypeError:
        return False


# Driver Code
for element in [34, [4, 5], "EyeHunts"]:
    print(element, " is iterable : ", iterable(element))

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 discuss 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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading