VOOZH about

URL: https://www.analyticsvidhya.com/blog/2023/06/python-for-loop/

⇱ Python For Loops: A Complete Guide - Analytics Vidhya


India's Most Futuristic AI Conference Is Back – Bigger, Sharper, Bolder

  • d
  • :
  • h
  • :
  • m
  • :
  • s

Guide to Python For Loops with Solved Examples

Analytics Vidhya Last Updated : 29 Jan, 2024
6 min read

Introduction

Consider that you are planning a concert and that you have a lineup of artists. You must now tell the audience each performer’s name. Each name would need to be announced separately, which would be very time-consuming and tiresome. Here, the Python for loop’s strength is put to use. It helps eliminate the requirement of separately writing the announcement for each performer. 

Here’s how it can be done:

performers = [“Ankit”, “Aryan”, “Bhavesh”, “Chirag”]

for performer in performers:

print(“Ladies and gentlemen, please welcome”, performer, “to the stage!”)

By using the for loop in this way, we can simply announce the names of each performer with only a few lines of code instead of having to create separate print statements for each performer.

We shall examine the Python for loop idea and its importance in programming in this post. For you to comprehend and master the Python for loop, we will delve into the syntax, examine cutting-edge strategies, and offer helpful examples. 

What is Python For Loop?

Python’s for loop is a key control structure that enables you to cycle through a list of items. By automating the repeated execution of a code block, you may effectively complete repetitive activities. To iterate across lists, tuples, strings, dictionaries, and other iterable objects, Python programmers frequently use the for loop.

👁 For loop
Source: Linux and Ubuntu

Also Read: Everything You Should Know About Built-In Data Structures in Python 

Basic Syntax of For Loop in Python

The syntax of a for loop in Python is straightforward. 

Here’s the basic structure:

for variable in iterable:

    # Code block to be executed

The variable represents the current element in the iteration, and the iterable is the sequence or collection over which the loop iterates. The code block indented under the for statement is executed for each element in the sequence.

Here is an example to help you understand the basic syntax of a for loop:

fruits = ["apple," "banana," "orange"]

for the fruit in fruits:

 print(fruit)

Now the for loop will iterate over the list of fruits, printing the name for each fruit.

Output:

apple

banana

Orange

Range Function and For Loop in Python

The range() function is commonly used for loops in Python. It creates a sequence of numbers that help determine the number of times the loop iterates. The three arguments for the range() function are as follows:

  • Start
  • Stop
  • Step

Here is an example of how to use a for loop and the range() function:

Example 1: range(6)

This variant generates a sequence of numbers starting from 0 (inclusive) up to, but not including, the specified stop value, which in this case is 6. It will generate the numbers 0, 1, 2, 3, 4, and 5. The general syntax is range(start, stop, step), but if you omit the start value, it defaults to 0, and if you omit the step value, it defaults to 1.

for i in range(6):

    print(i)

Output:

0

1

2

3

4

5

Example 2: range(3, 6)

This variant generates a sequence of numbers starting from the specified start value, which in this case is 3 (inclusive), up to, but not including, the specified stop value, which is 6. It will generate the numbers 3, 4, and 5.

for i in range(3, 6):

    print(i)

Output:

3

4

5

Example 3: for i in range(1, 6, 2)

for i in range(1, 6, 2)

    print(i)

Thus, the for loop will iterate over the numbers from 1 to 6 with a step of 2. 

Output:

1

3

5

Nested For Loop in Python

Python allows you to nest one or more loops within another loop. This is known as a nested for loop. These are helpful in conditions when you need to iterate over multiple sequences or carry out iterations within iterations.

Here’s an example of a nested for loop that prints the multiplication table from 1 to 5:

for i in range(1, 6):

    for j in range(1, 11):

        print(i * j, end="\t")

    print()

In this illustration, the inner for loop iterates from 1 to 10 while the outside for loop iterates over the integers 1 to 5. The multiplication table is produced and shown using the print() function.

Checkout: Everything a Beginner should know about Classes and Objects in Python Before Starting Your Data Science Journey

Control Statements in For Loop in Python

Python provides control statements such as break and continue that can be used within a for loop to control the flow of execution.

The break statement allows you to exit the loop prematurely based on a certain condition. It ends the loop and gives the next sentence, which follows the loop, control.

The continue statement advances to the following iteration without running the remaining code in the block for the current iteration. It gives you the option, under certain circumstances, to skip particular items in a sequence.

These control statements provide flexibility and enable you to fine-tune the behavior of your for loop based on specific requirements.

Break Example

for i in range(10):
 print(i)
 if i==5:
 break
print("loop ended")

Output:
0
1
2
3
4
5
loop ended

Continue Example


for i in range(10):
 print(i)
 if i==5:
 print("if condition checked, let's 'continue' ")
 continue
 print("This statement will not be printed because control has moved to the starting of loop.")

Output:
0
1
2
3
4
5
if condition checked, let’s ‘continue’
6
7
8
9

List Comprehension and For Loop in Python

List comprehension is a concise and powerful technique in Python that allows you to create new lists based on existing lists using a single line of code. It combines the for loop and an optional filtering condition within square brackets.

Here is an example that demonstrates list comprehension:

numbers = [1, 2, 3, 4, 5]

squared_numbers = [x ** 2 for x in numbers]

print(squared_numbers)

The for loop will iterate over each element in the numbers list, square it, and add it to the squared_numbers list.

Output:

[1, 4, 9, 16, 25]

List comprehension provides a concise and elegant way to manipulate lists, making your code more readable and expressive.

Iterating Through String and Tuple Using For Loop in Python

The for loop may cycle over other iterable objects besides lists, such strings and tuples. Each character in a string or each component of a tuple is treated as a separate item in the loop.

Here is an illustration of how to use a for loop to iterate over a string:

message = "Hello, Python!"

For char in message:

    print(char)

In this case, the for loop iterates and prints over each character in the message string. 

The output will be:

H

e

l

l

o

,

P

y

t

h

o

n

!

Similarly, using a for loop, you can iterate through tuples and perform operations based on individual elements.

Iterating Through Dictionaries Using For Loop in Python

Despite the fact that dictionaries lack the intrinsic iterability of lists or tuples, you may iterate using them in a loop. The loop iterates through the dictionary’s keys by default.

Example:

student_grades = {"Alice": 85, "Bob": 92, "Charlie": 78}

for student in student_grades:

    print(student, ":", student_grades[student])

In this example, the for loop iterates over each key in the student_grades dictionary and prints both the student’s name and their corresponding grade. The output will be:

Alice: 85

Bob: 92

Charlie: 78

To iterate over the values or both keys, you can use the values() method. On the other hand, to iterate over values of a dictionary, use the items() methods.

Conclusion

Mastering the for loop enables you to efficiently process data, automate repetitive tasks, and write more concise code. Remember to practice and experiment with different examples to solidify your understanding. So, start harnessing the potential of the for loop in Python and take your programming skills to the next level. Enroll in our free python course and learn all the major techniques!

Frequently Asked Questions

Q1. Can I have nested for loops in Python?

A. Yes, Python allows you to nest one or more loops within another loop. This is called a nested for loop. It is useful when you must iterate over multiple sequences or perform iterations within iterations.

Q2. What does Python’s list comprehension mean?

A. With only one line of code, you may build new lists based on existing ones using Python’s succinct and potent list comprehension approach. Within square brackets, it combines the for loop with a potential filtering condition.

Q3. Can I use a for loop to iterate through a string or a tuple?

A. Yes, a for loop can iterate through strings and tuples. Each character in a string or each element in a tuple is treated as an individual item in the loop, allowing you to perform operations based on those elements.

Analytics Vidhya Content team

Login to continue reading and enjoy expert-curated content.

Free Courses

Generative AI - A Way of Life

Explore Generative AI for beginners: create text and images, use top AI tools, learn practical skills, and ethics.

Getting Started with Large Language Models

Master Large Language Models (LLMs) with this course, offering clear guidance in NLP and model training made simple.

Building LLM Applications using Prompt Engineering

This free course guides you on building LLM apps, mastering prompt engineering, and developing chatbots with enterprise data.

Improving Real World RAG Systems: Key Challenges & Practical Solutions

Explore practical solutions, advanced retrieval strategies, and agentic RAG systems to improve context, relevance, and accuracy in AI-driven applications.

Microsoft Excel: Formulas & Functions

Master MS Excel for data analysis with key formulas, functions, and LookUp tools in this comprehensive course.

Responses From Readers

Flagship Programs

GenAI Pinnacle Program| GenAI Pinnacle Plus Program| AI/ML BlackBelt Program| Agentic AI Pioneer Program

Free Courses

Generative AI| DeepSeek| OpenAI Agent SDK| LLM Applications using Prompt Engineering| DeepSeek from Scratch| Stability.AI| SSM & MAMBA| RAG Systems using LlamaIndex| Building LLMs for Code| Python| Microsoft Excel| Machine Learning| Deep Learning| Mastering Multimodal RAG| Introduction to Transformer Model| Bagging & Boosting| Loan Prediction| Time Series Forecasting| Tableau| Business Analytics| Vibe Coding in Windsurf| Model Deployment using FastAPI| Building Data Analyst AI Agent| Getting started with OpenAI o3-mini| Introduction to Transformers and Attention Mechanisms

Popular Categories

AI Agents| Generative AI| Prompt Engineering| Generative AI Application| News| Technical Guides| AI Tools| Interview Preparation| Research Papers| Success Stories| Quiz| Use Cases| Listicles

Generative AI Tools and Techniques

GANs| VAEs| Transformers| StyleGAN| Pix2Pix| Autoencoders| GPT| BERT| Word2Vec| LSTM| Attention Mechanisms| Diffusion Models| LLMs| SLMs| Encoder Decoder Models| Prompt Engineering| LangChain| LlamaIndex| RAG| Fine-tuning| LangChain AI Agent| Multimodal Models| RNNs| DCGAN| ProGAN| Text-to-Image Models| DDPM| Document Question Answering| Imagen| T5 (Text-to-Text Transfer Transformer)| Seq2seq Models| WaveNet| Attention Is All You Need (Transformer Architecture) | WindSurf| Cursor

Popular GenAI Models

Llama 4| Llama 3.1| GPT 4.5| GPT 4.1| GPT 4o| o3-mini| Sora| DeepSeek R1| DeepSeek V3| Janus Pro| Veo 2| Gemini 2.5 Pro| Gemini 2.0| Gemma 3| Claude Sonnet 3.7| Claude 3.5 Sonnet| Phi 4| Phi 3.5| Mistral Small 3.1| Mistral NeMo| Mistral-7b| Bedrock| Vertex AI| Qwen QwQ 32B| Qwen 2| Qwen 2.5 VL| Qwen Chat| Grok 3

AI Development Frameworks

n8n| LangChain| Agent SDK| A2A by Google| SmolAgents| LangGraph| CrewAI| Agno| LangFlow| AutoGen| LlamaIndex| Swarm| AutoGPT

Data Science Tools and Techniques

Python| R| SQL| Jupyter Notebooks| TensorFlow| Scikit-learn| PyTorch| Tableau| Apache Spark| Matplotlib| Seaborn| Pandas| Hadoop| Docker| Git| Keras| Apache Kafka| AWS| NLP| Random Forest| Computer Vision| Data Visualization| Data Exploration| Big Data| Common Machine Learning Algorithms| Machine Learning| Google Data Science Agent
👁 Av Logo White

Continue your learning for FREE

Forgot your password?
👁 Av Logo White

Enter OTP sent to

Edit

Wrong OTP.

Enter the OTP

Resend OTP

Resend OTP in 45s

👁 Popup Banner
👁 AI Popup Banner