GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • tech beamers
  • Python Lab
  • Python Online Compiler
  • Python Code Checker
  • Python Coding Exercises
  • Python Coding Quizzes
  • SQL Practice
  • Selenium Practice
  • SW Guides
  • Meenakshi Agarwal

This view

  • Original page
  • New address

GeezerVison is showing techbeamers.com — Python Program: For Loop Examples

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
  • For Loop Examples in Python
    • Traverse a list of different items
    • Iterate the list from end using for loop
    • Example of Python for loop to iterate in sorted order
    • Using for loop to enumerate the list with index
    • Iterate 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.

Before reading this post, you should 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

Lastly, our site needs your support to remain free. Share this post on social media (Linkedin/Twitter) if you gained some knowledge from this tutorial.

Enjoy coding,
TechBeamers.

Share This Article
Whatsapp Whatsapp LinkedIn Reddit Copy Link
Meenakshi Agarwal Avatar
ByMeenakshi Agarwal
Follow:
I’m Meenakshi Agarwal, founder of TechBeamers.com and ex-Tech Lead at Aricent (10+ years). I built the Python online compiler, code checker, Selenium labs, SQL quizzes, and tutorials to help students and working professionals.
Previous Article Python IRC Bot Client Python Program: Learn to Build an IRC Bot
Next Article Search keys by values in a Python dictionary Python Program: Search Keys by Value in a Dictionary
Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Most Popular This Month

  • → Python Online Compiler
  • → Python Code Checker
  • → Free Python Tutorial
  • → SQL Practice Queries
  • → Code to Flowchart Tool
  • → Python Syntax Guide
  • → Python List & Dict Questions
  • → Selenium Practice Test Page

RELATED TUTORIALS

Replace all or specified no. of occurrences of chars sub strings in Python

Python Program: Replace Occurrences of a Character

By Meenakshi Agarwal
11 months ago
Python Sort Using Lambda With Examples

Python Program: How to Sort with Lambda

By Soumya Agarwal
11 months ago
Python Sort a List in Descending Order With Examples

Python Program: Sort List in Descending Order

By Soumya Agarwal
11 months ago
Generate Random Integer Numbers

Python Program: Generate Random Integer

By Meenakshi Agarwal
11 months ago
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.