Iterables in Python
FREE Online Courses: Knowledge Awaits – Click for Free Access!
Iterables is one of the basic and most important concepts of Python. In this article, we learn about iterables, their types, and several other functions that help us when working with iterables.
What are iterables in python?
Iterables are containers that can store multiple values and are capable of returning them one by one. Iterables can store any number of values. In Python, the values can either be the same type or different types. Python has several types of iterables.
Types of Iterables in Python
1. List in python
A list is the most common iterable and most similar to arrays in C. It can store any type of value. A list is a mutable object. The values in the list are comma-separated and are defined under square brackets []. We can initialize a list using the square brackets or using the list() function.
Example of list in Python
li = [1, 2, 3, "PythonGeeks"] #initializing a list with multiple values print(li) li2 = list() #initializing a list using the function print(li2) li3 = [345] #initializing a list with one value print(li3)
Output
[]
[345]
2. Tuple in Python
Unlike lists, a tuple is an immutable object. Tuple can store any type of value. The values in the tuple are comma-separated and are defined under parenthesis (). We can initialize a tuple using the parenthesis or the function tuple().
Example of tuple in Python
tup = (1, 2, 3, "PythonGeeks") print(tup) tup1 = tuple() print(tup1) tup2 = (34) print(tup2) tup3 = (1, 1, 1, 1, 5, 4) print(tup3)
Output
()
34
(1, 1, 1, 1, 5, 4)
3. Set in Python
Set is a mutable and ordered object. It can store any type of object. The values in the set are comma-separated and are defined under braces {}. We can initialize a set using the braces or the function set().
Example of set in Python
set_0 = {1, 2, 3, "PythonGeeks"} print(set_0) set1 = set() print(set1) set2 = {34} print(set2) set3 = {1, 1, 1, 1, 5, 4} print(set3)
Output
set()
{34}
{1, 4, 5}
Functions for Iterables in Python
Python provides various useful functions that we can use on iterables. Iterables are accepted as arguments by these functions. The following are some examples of such functions.
1. list() in Python
list() can accept an iterable as an argument and returns another iterable.
Example of using list() in Python
a = list("PythonGeeks") print(a)
Output
2. sorted() in Python
The function takes an iterable as an argument and sorts the values in the passed iterable. By default, it sorts the values in ascending order.
Example of using sorted() in Python
a = [3, 2, 4, 10, 1] b = sorted(a) print(b)
Output
3. max() in Python
The function returns the maximum/highest value in the passed iterable.
Example of using max() in Python
a = [3, 2, 4, 10, 1] b = max(a) print(b)
Output
4. min() in Python
The function returns the minimum/lowest value in the passed iterable.
Example of using min() in Python
a = [3, 2, 4, 10, 1] b = min(a) print(b)
Output
5. all() in Python
The function returns either True or False depending on the values in the passed iterable. If all values are true, then it returns True. It returns False if at least one value is false.
Example of using all() in Python
a = [3, 1, 2] b = [3, 1, 0] print(all(a), all(b))
Output
6. any() in Python
The function returns True if atleast one value is True in the passed iterable. It returns False if no value is True in the iterable. The function stops the iteration as soon as it finds the true value.
Example of using any() in Python
a = [3, 1, 0] b = [0, 0, 0] print(any(a), any(b))
Output
7. sum() in Python
The function adds all values in the passed iterable and returns the sum. It raises a TypeError if the iterable has any unsupported data type such as string.
Example of using sum() in Python
a = [24, 25] b = sum(a) print(b)
Output
Unpacking Iterables in Python
Unpacking iterables means assigning each value in an iterable to a separate variable. The conventional way of unpacking is using the index of the value.
Example of unpacking iterables in Python
li = [1, "PythonGeeks"] var1 = li[0] var2 = li[1] print(var1) print(var2)
Output
PythonGeeks
Although this method does the job, Python provides us an easier, and an efficient way of unpacking values from an iterable.
Syntax
var1, var2,.....,varN = [value1, value2,...., valueN]
Example of unpacking iterables in Python
li = [1, "PythonGeeks"] var1, var2 = li print(var1) print(var2)
Output
PythonGeeks
Unpacking in For-Loop
We can also unpack a nested iterable in the for-loop. Python allows us to use the previously mentioned unpacking method in for-loops.
Example of unpacking an iterable in Python
li = [[1, "PythonGeeks"], [2, "HelloWorld"]] for num, str in li: print(num) print(str)
Output
PythonGeeks
2
HelloWorld
Enumerating Iterables in Python
The function enumerate() helps us to keep a count on iteration while using for-loop.
Example of using enumerate() in Python
li = ["PythonGeeks", "Hello World"] for num, str in enumerate(li): print(num, "--", str)
Output
1 — Hello World
Identifying whether or not objects are iterables in Python
Although Python has no function to directly check whether an object is iterable not, we can still do it indirectly using other functions.
We can identify whether an object is iterable by using the collections module and isinstance() function.
Example of using isinstance() in Python
from collections.abc import Iterable li = [1,2,3,4] var1 = 16 print(isinstance(li, Iterable)) print(isinstance(var1, Iterable))
Output
False
One other way of checking whether an object is iterable or not is by using the iter() function. Passing a non-iterable object to the function raises an error. So, we can pass the object that we want to check and if the function raises an error, then it is not iterable. If it runs successfully without an error, then it is iterable.
Example of using iter() in Python
li = [1,2,3,4] var1 = 16 try: iter(li) except: print("Not an iterable") else: print("An iterable") try: iter(var1) except: print("Not an iterable") else: print("An iterable")
Output
Not an iterable
Python Interview Questions on Iterables
Q1. Initialize an empty immutable iterable and print it.
Ans 1. Complete code is as follows:
iterable = tuple() print(iterable)
Output
Q2. Initialize a mutable iterable with at least three strings and two integers. Print the iterable.
Ans 2. Complete code is as follows:
programming = ["Python", "C++", "Java", 1, 2] print(programming)
Output
Q3. Write a program to unpack iterable named students containing four values.
Ans 3. Complete code is as follows:
students = ["Sam", "Ram", "Jim", "Kim"] student1, student2, student3, student4 = students print(student1, student2, student3, student4)
Output
Q4. Write a program to check whether the given object is iterable or not.
Ans 4. Complete code is as follows:
from collections.abc import Iterable obj1 = {32} print(isinstance(obj1, Iterable))
Output
Q5. Write a program to remove all the duplicated values in the following list and sort the values in ascending order without using any loops.
List = [5,5,5,1,1,11,4,2,3]
Ans 5. Complete code is as follows:
List = [5, 5, 5, 1, 1, 11, 4, 2, 3, 3, 3] answer = set(List) print(answer)
Output
Quiz on Python Iterables
Conclusion
In this article, we learned about the meaning of iterables. We discussed the different types of iterables and understood when to use which iterable. We learned how to unpack iterables in a single line and enumerate those iterables in a loop. Finally, we learned multiple ways of identifying whether an object is iterable or not. Additionally, if you have any feedback, please post it in the comments area.
The answer to question 7 is 36 not 4. I was afraid I was missing something, so I copied and pasted the code into Python, returned 36.
Thought I was going mad on Q7. Me too!
Set is not ordered. Please correct your blog
As @deepak mentioned, a Set is NOT ordered. Additionally it cannot have any duplicates. Please correct as it is confusing.
There’s an error in the “Tuples” examples:
tup2 = (34)
print(tup2)
tup2 is NOT a tuple. It should be:
tup2 = (34,)
print(tup2)
and the output should then be (34,) and not 34.
Nearly 2 years later and the answer to question 7 is still wrong.
I just want to point out that both times you used “parenthesis” should be “parentheses.” “Parenthesis” is singular, whereas “parentheses” is plural.