Home > Mobile >  How can I iterate on python list by choosing and then removing each item?
How can I iterate on python list by choosing and then removing each item?

Time:10-05

So I have this dict i take from some page using request. Now i use its values to create list. How can I iterate on that list to extract and use each item? I have already tried something like this:

  for component in values:
        if values.index(component) > 0:
            value = values.pop()

but its give me only some items and leave others.

CodePudding user response:

It looks like you only need to iterate over the list, not remove any elements. If you want to create a list from an existing one, you can use the list comprehension:

same_values = [x for x in values]

And if you want, you can add a specific condition:

positive_values = [x for x in values if x > 0]

CodePudding user response:

Given, you got a dictionary and need the values in the form of a list. Let dct be your dictionary, then extract the values from the dictionary...

list_values = list( dct.values() )

If you want to filter the values based on the index of the dictionary, then you can use the below code to filter the values based on the index from the dictionary.

for i, j in zip( dct.keys(), dct.values() ):
    if i > 0:
        print(j)

The functions keys() and values() returns the indexes and values at that index separately, which are joined using the zip function and stored into i and j respectively at each iteration of the for-loop.

  • Related