TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Python For Loop Examples
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python ExamplesPython Tutorials

Python For Loop Examples

Last updated: Nov 05, 2023 12:06 am
By Meenakshi Agarwal
Share
6 Min Read
Various Python for loop example
SHARE

In this post, you will see and learn the usage of for loop in Python with examples. Here, we’ll mainly focus on iterating the list object using the “for loop” construct in different ways.

Contents
Traverse a list of different itemsIterate the list from end using for loopUsing the reversed() functionReverse a list in for loop using the slice operatorExample of Python for loop to iterate in sorted orderUsing for loop to enumerate the list with indexIterate multiple lists with for loop in Python

The lists in Python are hybrid data structures that can hold a variety of values. We’ll try to demonstrate the use of a for loop to traverse a sequence with the help of examples.

Prior to reading this post, it is advisable that you know how the for loop works in Python. It will help you learn the lopping basics and techniques for fast traversing.

For Loop Examples in Python

You have read about Python for loop in our previous tutorials. It is much more flexible than the loops available in other languages. You can apply them to perform interesting programming tasks.

Let’s check out some examples:

Traverse a list of different items

It is one of the most common examples where Python for loop can be used. Say, you have a list that contains strings and numbers. And you have to iterate each element one by one.

So, you should be using the for loop in the following manner:

#Initialize a sequence
elements = ["Python", 3, 8, "CSharp", "PHP"]

#for each element in the list, iterate the list
for ele in elements:
    # print the element
    print((ele), end = " ")

Output

Result...
Python 3 8 CSharp PHP 
CPU Time: 0.02 sec(s), Memory: 8328 kilobyte(s)executed in 0.652 sec(s)

Iterate the list from end using for loop

In this section, we’ll see how to print each item on the list in reverse order. To do so, you can follow one of the methods given below.

Using the reversed() function

It inverts the order of a list. Go over the below sample code.

#Prepare a list
elements = ["Python", 3, 8, "CSharp", "PHP"]

#Iterate the list in reverse order
for ele in reversed(elements):
    # print the element
    print((ele), end = " ")

Output

Result...
PHP CSharp 8 3 Python
CPU Time: 0.03 sec(s), Memory: 8484 kilobyte(s)

Reverse a list in for loop using the slice operator

#Prepare a list
elements = ["Python", 3, 8, "CSharp", "PHP"]

#Reverse the list using slice operator
for ele in elements[::-1]:
    # print the element
    print((ele), end = " ")

Output

Result...
PHP CSharp 8 3 Python 
CPU Time: 0.04 sec(s), Memory: 8348 kilobyte(s)

Example of Python for loop to iterate in sorted order

You can also enumerate a list in the sorted order using a for loop. To do so, Python provides the sorted() function. It modifies the order of a sequence.

Check out the following sample code.

#Prepare a list of numbers
elements = [11, 23, 43, 17, 32]

#Run a for loop on a sorted list
for ele in sorted(elements):
    # print the element
    print((ele), end = " ")

Output

Result...
11 17 23 32 43 
CPU Time: 0.03 sec(s), Memory: 8480 kilobyte(s)

Using for loop to enumerate the list with index

In Python, the enumerate() function is available that you can call over a sequence and get the indexes of elements in each iteration.

Copy/paste the following code and try it out yourself.

#Prepare a list of numbers
elements = [11, 23, 43, 17, 32]

#Run a for loop on a sorted list
for index, data in enumerate(elements):
    # show the index and the value stored
    print("Element value of {} := {}".format(str(index), str(data)))

Output

Result...
Element value of 0 := 11
Element value of 1 := 23
Element value of 2 := 43
Element value of 3 := 17
Element value of 4 := 32
CPU Time: 0.02 sec(s), Memory: 8352 kilobyte(s)

Iterate multiple lists with for loop in Python

Imagine a scenario, where you have a sequence of countries and also have another list of capitals. Now, write Python code to print the summary of countries with their capital cities.

Check out the below Python for loop example to accomplish this. Here we called the Python zip function to combine multiple lists.

countries = [ 'USA', 'Germany', 'France', 'India', 'China' ]
capitals = [ 'Washington, D.C.', 'Berlin', 'Paris', 'Delhi', 'Beijing']
population = [ 702000, 3570000, 2140000, 19000000, 21500000]

#Consolidate three lists using the zip() function
print("{0:<10} {1:<20} {2:>5}".format("#Country", "#Capital","#Population"))
for country, capital, size in zip(countries, capitals, population):
    print("{0:<10} {1:<20} {2:>5}".format(country, capital, size))

Output

Result...
#Country   #Capital             #Population
USA        Washington, D.C.     702000
Germany    Berlin               3570000
France     Paris                2140000
India      Delhi                19000000
China      Beijing              21500000
CPU Time: 0.02 sec(s), Memory: 8460 kilobyte(s)

In the above example, we used the format function with alignments to print the intuitive summary. Read the below tutorial to learn more about such formatting.

Also Check: Format strings in Python

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Format or percentage for string formatting in Python Python String Formatting Methods
Next Article Search keys by values in a Python dictionary Search Keys by Value in a Dictionary

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x