-1

I have an error w.r.t list inside a list. I am trying to assign the elements to a variable. So whatever I insert in those list inside the list it will get assigned to those variables. Like show below

list = [[1, 2], [2, 3], [4, 5]]
car = list[0]
bike = list[1]
cycle = list[3]

Now, suppose I won't give a value for the 3rd list(like shown below). Then I will get an error:

list[[1, 2], [2, 3]]
car = list[0]
bike = list[1]
cycle = list[3]

Error message: List index out of range

So, I wrote a condition which should ignore it. But I am getting a error. How to ignore if the values is not given?

My code:

if list[0] == []:
    continue
else:
    car = list[0]
if list[1] == []:
    bike = list[1]
if list[2] == []:
    cycle = list[2]

SyntaxError: 'continue' not properly in loop

Where am I going wrong? How to give an if condition if there is no list in it? Did I give it correctly?

Lukas Thaler
  • 2,672
  • 5
  • 15
  • 31
  • Check length maybe and perform the assignment accordingly – coldy Mar 15 '21 at 21:52
  • The syntax error is telling you that you can't use `continue` somewhere that's not in a loop. What did you expect it to do? – khelwood Mar 15 '21 at 21:53
  • Do not call your own variable `list`. That's the name of a type. – Tim Roberts Mar 15 '21 at 21:54
  • Does this answer your question? [syntaxError: 'continue' not properly in loop](https://stackoverflow.com/questions/14312869/syntaxerror-continue-not-properly-in-loop) – Sören Jun 11 '22 at 09:45

3 Answers3

0

Just do it like you would say it in words.

lst = [[1,2],[2,3],[4,5]]
if len(lst) > 0:
    car = lst[0]
if len(lst) > 1:
    bike = lst[1]
if len(lst) > 2:
    cycle = lst[2]
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
0

If I understood your problem correctly, what you're looking for is a try/except statement. This allows you to do as follows:

try:
    car = list[0]
    bike = list[1]
    bike = list[2]
except IndexError:
    pass

This code allows you to execute the block "try" until there's an exception, and if an error is catched you just continue the loop. For example you could put something like this inside a for loop as follows:

for list in my_list_of_lists:
    try:
        car = list[0]
        bike = list[1]
        bike = list[2]
    except IndexError:
        continue

finally, regarding this

SyntaxError: 'continue' not properly in loop

if you use the break/continue/pass statements they should always be inside a for or while loop, as I've shown above.

fcagnola
  • 640
  • 7
  • 17
0

Given:

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

And variable index, with an integer value you want to use to index the list.

A few options:

  1. Check if the length of the list is smaller then the index you want to extract.
    if len(a) > index:
        nested_list = a[index]
  1. Just try it.
    try:
        nested_list = a[index]
    except IndexError as e:
        print(f'index invalid {e}')
        # fallback condition
        nested_list = []
Woody
  • 76
  • 3