0

I have list1,list2, list4... and want to print them out one by one using a for loop with range(5).

How can I skip the list0 and list3

Also, the variable file into the print(file) yet.

Can you please help?

Thank you, HN

list1={1,10}
list2={2,20}
list4={4,40}

for i in range(5):
    file='list'+str(i)
    print(file)
  • Do some basic tutorials on how to loop over a list. [Here is one](https://www.w3schools.com/python/python_lists_loop.asp). – Bill Jun 10 '21 at 03:42

3 Answers3

0

If you want to skip an iteration of a loop, use the continue keyword:

list1={1,10}
list2={2,20}
list4={4,40}

for i in range(5):
    if i == 0 or i == 3:
        continue
    file='list'+str(i)
    print(file)

As a side note, your variable names are misleading, because {1,10} is the syntax for a set literal, not a list (which would be [1,10]). Unlike lists, sets cannot hold duplicates. Read this post for more differences.

Andrew Eckart
  • 1,497
  • 7
  • 12
0

You can test if the variables exist locally or globally:

list1={1,10}
list2={2,20}
list4={4,40}

for i in range(5):
    file='list'+str(i)
    if file not in locals() and file not in globals():
        continue
    print(file)
thshea
  • 993
  • 4
  • 17
0

Well I think your problem can be easily fixed like so.

name = ('list1','list2','list4')

for i in range(5):
  if f"list{i}" in name:
    file = f"list{i}"
    print(file)
Alpha Wolf Gamer
  • 275
  • 2
  • 10