Python Tutorial - Master Python Programming For Beginners from Scratch

  • Home
  • Getting Started
  • Basics
  • OOP
  • Advanced Python
  • Tkinter
Home » Python Basics » Python Iterables

Python Iterables

Summary: in this tutorial, you’ll learn about the Python iterables and iterators.

Introduction to Python iterables

In Python, an iterable is an object that includes zero, one, or many elements. An iterable has the ability to return its elements one at a time.

Because of this feature, you can use a for loop to iterate over an iterable.

In fact, the range() function is an iterable because you can iterate over its result:

for index in range(3): print(index)
Code language: Python (python)

Output:

0 1 2
Code language: Python (python)

Also, a string is an iterable because you can use a for loop to iterate over it:

str = 'Iterables' for ch in str: print(ch)
Code language: Python (python)

Lists and tuples are also iterables because you can loop over them. For example:

ranks = ['high', 'medium', 'low'] for rank in ranks: print(rank)
Code language: Python (python)

The rule of thumb is that if you know if can loop over something, it’s iterable.

What is an iterator

An iterable can be iterated over. And an iterator is the agent that performs the iteration.

To get an iterator from an iterable, you use the iter() function. For example:

colors = ['red', 'green', 'blue'] colors_iter = iter(colors)
Code language: Python (python)

Once you have the iterator, you can get the next element from the iterable using the next() function:

colors = ['red', 'green', 'blue'] colors_iter = iter(colors) color = next(colors_iter) print(color)
Code language: Python (python)

Output:

red
Code language: Python (python)

Every time, you call the next() function, it returns the next element in the iterable. For example:

colors = ['red', 'green', 'blue'] colors_iter = iter(colors) color = next(colors_iter) print(color) color = next(colors_iter) print(color) color = next(colors_iter) print(color)
Code language: Python (python)

Output:

red green blue
Code language: Python (python)

If there isn’t any more element and you call the next() function, you’ll get an exception.

colors = ['red', 'green', 'blue'] colors_iter = iter(colors) color = next(colors_iter) print(color) color = next(colors_iter) print(color) color = next(colors_iter) print(color) # cause an excpetion color = next(colors_iter) print(color)
Code language: Python (python)

This example first shows three elements of the colors list and then issues an exception:

red green blue Traceback (most recent call last): File "iterable.py", line 15, in <module> color = next(colors_iter) StopIteration
Code language: Python (python)

The iterator is stateful. It means that once you consume an element from the iterator, it’s gone.

In other words, once you complete looping over an iterator, the iterator becomes empty. If you iterate over it again, it’ll return nothing.

Since you can iterate over an iterator, the iterator is also an iterable object. This is quite confusing. For example:

colors = ['red', 'green', 'blue'] iterator = iter(colors) for color in iterator: print(color)
Code language: Python (python)

Output:

red green blue
Code language: Python (python)

If you call the iter() function and pass an iterator to it, it’ll return the same iterator back.

Later, you’ll learn how to create iterables.

Summary

  • An iterable is an object that can be iterated over. An iterable has the ability to return one of its elements at a time.
  • An iterator is an agent that performs iteration. It’s stateful. And an iterator is also an iterable object.
  • Use the iter() function to get an iterator from an iterable object and the next() function to get the next element from the iterable object.
  • Was this tutorial helpful ?
  • YesNo
Previous How to Find the Index of an Element in a List
Next How to Transform List Elements with Python map() Function

Getting Started

  • What is Python
  • Install Python
  • Setup VS Code for Python
  • Develop Python Hello World Program

Python Fundamentals

  • Python Syntax
  • Variables
  • Strings
  • Numbers
  • Boolean
  • Constants
  • Comments
  • Type Conversion

Control Flow

  • if…else
  • Ternary Operator
  • for Loop
  • while Loop
  • break
  • continue
  • pass

Functions

  • Python Functions
  • Default Parameters
  • Keyword Arguments
  • Recursive Functions
  • Lambda Expressions
  • Function Docstrings

Python List

  • List
  • Tuple
  • Sorting a List in Place: sort()
  • Sorting a List: sorted()
  • Slicing a List: [::]
  • Unpacking a List
  • Iterating over a List: for loop
  • Finding Index of an Element: index()
  • Iterables
  • Transform List Elements: map()
  • Filtering List Elements: filter()
  • Reducing List Elements: reduce()
  • List Comprehensions

Python Dictionary

  • Dictionary
  • Dictionary Comprehension

Python Set

  • Set
  • Set Comprehension
  • Union of Sets
  • Intersection of Sets
  • Difference between Sets
  • Symmetric Difference of Sets
  • Subset
  • Superset
  • Disjoint Sets

Exception Handling

  • try…except
  • try…except…finally
  • try…except…else

Python Loop with Else Clause

  • for…else
  • while…else
  • do…while Emulation

More on Functions

  • Unpacking Tuples
  • The *args Parameters
  • The **kwargs Parameters
  • Partial Functions

Modules

  • Modules
  • Module Search Path
  • Python __name__
  • Packages

File I/O

  • Reading a Text File
  • Writing to a Text File
  • Creating a Text File
  • Checking If a File Exists
  • Reading from a CSV File
  • Writing to a CSV File

Managing Third-party Packages

  • Python Package Index (PyPI) & PIP
  • Python Virtual Environments
  • Install pipenv on Windows
  • Using pipenv Tool

About pythontutorial.net

Pythontutorial.net helps you master Python programming from scratch fast.

Site Links

  • Home
  • Contact
  • About
  • Privacy Policy

Recent Python Tutorials

  • Tkinter StringVar
  • Tkinter PhotoImage
  • Tkinter OptionMenu
  • Tkinter ScrolledText
  • How to Change the Appearances of Widgets Dynamically Using Ttk Style map() Method

Python References

  • Python String Methods
  • Python MySQL
  • Python PostgreSQL
  • Python Oracle
  • Python SQLite

Copyright © 2021 · by pythontutorial.net. All rights reserved. Log in