Home > front end >  python loop over all vars in list from a specific index
python loop over all vars in list from a specific index

Time:06-08

I am new to python. I'm trying to take all list's variables in the following manner:

  1. Im going through the list and find the variable that I want.
  2. From that variable, I want to copy to a new list all the other list's variables starting from the variable I found 2.

For Example:

#If I go through this list until I find "0.1.0-730b9a1": 
versions_list= ["0.1.0-3572c21", "0.1.0-730b9a1", "0.0.2", "0.0.1", "0.0.3"]

#I want to be able to take all the rest of the items in the list from "0.1.0-730b9a1"   2, to a new list.
#Means, my new list should contain only: 
["0.0.1", "0.0.3"]

In my code, when I find that version equals to "revision" in versions.yaml, I try to take all versions from versions_list starting from version 2 to a new list called final_list:

import yaml

versions_list= ["0.1.0-3572c21", "0.1.0-730b9a1", "0.0.2", "0.0.1", "0.0.3"]
final_list= []
found = 0 
with open('versions.yaml', 'r') as file:
    catalog = yaml.safe_load(file)
                
for version in versions_list:    
    for item, doc in catalog.items():
        for key in doc:
          if key['revision'] == version:
            found = 1
            for item in versions_list[version   2:]:
              final_list.append(versions_list[item])
    if found: break
print(final_list)

From the error I get, python is thinking that I am trying to concatenate string with int:

Traceback (most recent call last):
  File "mycode.py", line 14, in <module>
    for item in versions_list[version   2:]:
TypeError: can only concatenate str (not "int") to str

I expect the following output:

["0.0.1", "0.0.3"]

CodePudding user response:

The problem you are facing is that for version in versions_list iterates over the string values. You would like to access the index of the item which can be achieved by wrapping it in an enumerate:

for idx, version in enumerate(versions_list):
    ...
    for item in versions_list[idx   2:]:

CodePudding user response:

You could do the following:

versions_list= ["0.1.0-3572c21", "0.1.0-730b9a1", "0.0.2", "0.0.1", "0.0.3"]
rev = "0.1.0-730b9a1"
versions_list[versions_list.index(rev) 2:]

It will give ['0.0.1', '0.0.3']

index will give you the position of the element you are looking for, and using slicing of that position ( 2) you could get the desired results.

Note that if the element is not in the list it will raise ValueError. So you should test for it before, something like:

versions_list[versions_list.index(rev[:-3]) 2:] if rev[:-3] in versions_list else None

CodePudding user response:

I would suggest try/except as an efficient and robust way of doing this:

versions_list= ["0.1.0-3572c21", "0.1.0-730b9a1", "0.0.2", "0.0.1", "0.0.3"]
rev = "0.1.0-730b9a1"
try:
    idx = versions_list.index(rev)
    result = versions_list[idx 2:]
except ValueError:
    result = []
print(result)
  • Related