Python Forum
if statement in for loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
if statement in for loop
#1


I want to add an if statement in to a for loop so that if the statement is false, then the loop stops. something like this:
for i in range(0, len(list_of_nums) if list_of_nums[-1] != list_of_nums[i]:
is it possible?
i know u can use this structure to build lists, like:
x = [y for y in list_ if statement]
but i couldnt put it as i wanted...
Reply
#2
You can only put them like that because of list comprehensions.

Dont use range(len()) in a for loop in python
https://python-forum.io/Thread-Basic-Nev...n-sequence

You can just simplify it by looping a spliced version removing the last index
for num in list_of_nums[:-1]:
Recommended Tutorials:
Reply
#3
(Nov-12-2017, 10:03 AM)metulburr Wrote: You can only put them like that because of list comprehensions.

Dont use range(len()) in a for loop in python
https://python-forum.io/Thread-Basic-Nev...n-sequence

You can just simplify it by looping a spliced version removing the last index
for num in list_of_nums[:-1]:

Ok got it, but what if i do want the length of a string/list for 'i' to run through? and i dont care about the values inside the list...
what other choices i have except puting range(len()) on it?
Reply
#4
mylist = [56, 78, 94]
for count, _ in enumerate(mylist):
    print(count)
    
mystring = "Hello World!"
for count, _ in enumerate(mystring):
    print(count)
I am trying to help you, really, even if it doesn't always seem that way
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  While loop and If Statement farzankh 3 3,222 Jan-27-2019, 10:13 PM
Last Post: stullis
  Help converting int to str value in loop statement Jrvelandia 2 2,565 Feb-12-2018, 08:57 AM
Last Post: Jrvelandia

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020