Python if last in loop

Python For Loop with If Statement

What is the need for an if statement inside for loop in Python and how to use it? We can iterate blocks of code using for loop and using an if statement along with it we can check for a specific condition and perform until the condition is False . For loop iterates over a sequence(such as a list, or tuple) and execute a specific action for each item in the sequence. In this article, I will explain the concept of an if statement within for loop with examples.

Below are some use cases of using if Statement with for Loop:

  • if statement is used to check the condition of the iteration item.
  • break statement is used mostly with if statement to break the loop.
  • continue statement is used to skip the current iteration and go to the next one.
Читайте также:  Facebook php ads sdk

1. Quick Examples of For Loop with If Statement

Following are the quick examples of using For Loop with If statement

2. Python For Loop with If Statement

Using for loop with an if statement in Python, we can iterate over a sequence and perform different tasks for each item in a sequence until the condition falls a False. Let’s take two sets of lists and perform them using for loop with an if statement,

Python for loop with if

From the above, using for loop we have iterated each item in a given list named courses . For every iteration, it will check if the item of courses presents in another list named courses1. If the item presents both two lists then will print the item as a output.

3. For Loop with If Statement and Else statement

Let’s take another example using for loop with if statement and else statement.

Here, For every iteration, it will check if the item of i==java then the loop will be terminated and else block won’t execute.

If the i!=java then the if condition will not be executed and our program will not reach the break statement to terminate the loop. Only then the else block will execute.

Python for loop with if

4. Using For Loop with If Statement and Continue

Below are some more examples we are going to see on a for loop with a break, continue, and if statements.

Using the if statement along with the continue statement we can skip the current iteration of the loop within a specific condition and continue to the next iteration of the loop.

Here, I have taken courses as a list, which is iterated using for loop with the continue statement. Here as you can see continue statement is used within the if condition. If the loop reaches the ‘pandas’ the condition in the if the statement becomes True, so the continue statement will execute and skips the current iteration(pandas) and go for the next iteration.

Note: continue statement doesn’t exit the for/while loop.

5. Using For Loop with If Statement and Break

Sometimes you would like to exit from the python for / while loop when you meet certain conditions, using if and break statement you can exit the loop when the condition meets. The example is given below.

From the above example, I have taken the courses variable as a list that is iterated using for loop. We have applied a break statement based on x == ‘pandas’ condition. If the iteration reaches the pandas value, the for loop will exit using a break statement.

The above example exits loop when x value equals to pandas .

6. Nested for Loop with If Statement

If a loop presents inside the body of another loop is called a nested loop . The inner loop will be executed n number of times for each iteration of the outer loop within a specific condition using if statement. The example is given below.

If the break statement is inside a nested loop, the break statement will end the innermost loop and the outer loop continue executing. Let’s take an example for a better understanding.

In the above example, the inner loop will be executed three times(‘pandas’, ‘java’, ‘python’) for each iteration of the outer loop.

  • java, pandas
  • java, java in this case, the condition satisfies so the innermost loop ends. Then the control goes to the outer loop.
  • python, pandas
  • python, java
  • python, python in this case, the condition satisfies so the innermost loop ends.

7. Conclusion

In this article, I have explained the concept of an if statement within a for loop in Python and used these combinations while iterating how we can control and perform the given sequence with examples. Also learned the significance of the if statement to break & continue the looping.

References

You may also like reading:

Источник

Python if last in loop

Last updated: Feb 20, 2023
Reading time · 4 min

banner

# Table of Contents

# Detect the last item in a list using a for loop in Python

To detect the last item in a list using a for loop:

  1. Use the enumerate function to get tuples of the index and the item.
  2. Use a for loop to iterate over the enumerate object.
  3. If the current index is equal to the list’s length minus 1 , then it’s the last item in the list.
Copied!
my_list = ['one', 'two', 'three', 'four'] for index, item in enumerate(my_list): if index != len(my_list) - 1: print(item, 'is NOT last in the list ✅') else: print(item, 'is last in the list ❌')

detect last item in list using for loop

We used the enumerate() function to get an enumerate object we can iterate over.

The enumerate function takes an iterable and returns an enumerate object containing tuples where the first element is the index and the second is the item.

Copied!
my_list = ['one', 'two', 'three', 'four'] # 👇️ [(0, 'one'), (1, 'two'), (2, 'three'), (3, 'four')] print(list(enumerate(my_list)))

We used a for loop to iterate over the enumerate object and on each iteration, we check if the current index is NOT equal to the last index in the list.

# Checking if the current index is equal to the last index

If the current index is not equal to the last index in the list, then the element is not the last list item.

Copied!
my_list = ['one', 'two', 'three', 'four'] for index, item in enumerate(my_list): if index != len(my_list) - 1: print(item, 'is NOT last in the list ✅') else: print(item, 'is last in the list ❌')

check if current index is equal to last index

Python indexes are zero-based, so the first index in a list is 0 , and the last index is len(my_list) — 1 .

# Checking if we are on the last iteration of the loop

If you need to check if the element is the last list item, change the not equals (!=) operator to the equals (==) operator.

Copied!
my_list = ['one', 'two', 'three', 'four'] for index, item in enumerate(my_list): if index == len(my_list) - 1: print(item, 'is last in the list ✅') else: print(item, 'is NOT last in the list ❌')

check if we are on the last iteration of the loop

The example checks if the current index is equal to the last index in the list.

# Not performing an operation for the Last item in the List

If you don’t want to perform an operation for the last item in the list, use a list slice that excludes it.

Copied!
my_list = ['one', 'two', 'three', 'four'] for item in my_list[:-1]: print(item, 'is NOT last in the list ✅') print(my_list[-1], 'is last in the list ❌')

not performing an operation for the last item in the list

The my_list[:-1] syntax returns a slice of the list that excludes the last element.

The syntax for list slicing is my_list[start:stop:step] .

The slice in the example starts at index 0 and goes up to, but not including the last item in the list.

Negative indices can be used to count backward, e.g. my_list[-1] returns the last item in the list and my_list[-2] returns the second-to-last item.

# Joining without a separator after the last item

If you need to join the items in the list with a string separator, but don’t want to add the separator after the last element, use the str.join() method.

Copied!
my_list = ['one', 'two', 'three', 'four'] result_1 = '_'.join(my_list) print(result_1) # 👉️ 'one_two_three_four' result_2 = ' '.join(my_list) print(result_2) # 👉️ 'one two three four'

join without separator after last item

The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

If your list contains numbers or other types, convert all of the values to string before calling join() .

Copied!
my_list = ['one', 1, 'two', 2, 'three', 3] list_of_strings = list(map(str, my_list)) result_1 = '_'.join(list_of_strings) print(result_1) # 👉️ 'one_1_two_2_three_3' result_2 = ' '.join(list_of_strings) print(result_2) # 👉️ 'one 1 two 2 three 3'

The string the method is called on is used as the separator between the elements.

If you don’t need a separator and just want to join the iterable’s elements into a string, call the join() method on an empty string.

Copied!
my_list = ['one', 'two', 'three'] result_1 = ''.join(my_list) print(result_1) # 👉️ 'onetwothree'

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью