Exclude values from a python list

1

I am looking to do something similar to this, for each item of the array url minus the item index 0:

url = ['a.com', 1, 2, 3, 4, 5, 6, 7]
for item in url[0,1,2,3,4,5,6,7]:
    data ={
        "adSize": {"id":'{}'.format(item) }
        }

but in this way I have the following error message:

  

TypeError: list indices must be integers, not tuple

    
asked by Martin Bouhier 14.02.2018 в 23:49
source

2 answers

2

url[0,1,2,3,4,5,6,7] is an incorrect syntax, as the error shows the index of a list must be an integer. 0,1,2,3,4,5,6,7 is just syntactic sugar to create a tuple, that is, the above equals url[(0,1,2,3,4,5,6,7)] .

If you want to iterate over all the elements of a list except the first you have several options:

  • Slicing:

    url = ['a.com', 1, 2, 3, 4, 5, 6, 7]
    for item in url[1:]:
        print(item)
    

    Simple and good option for lists with few elements, but creates a copy of the object which is not very efficient for lists with many elements.

  • Use an iterator and consume the first element before for . Possibly the best option for relatively long lists:

    url = ['a.com', 1, 2, 3, 4, 5, 6, 7]
    
    url_iter = iter(url)
    next(url_iter)
    
    for item in url_iter:
        print(item)
    
  • Use itertools.islice :

    from itertools import islice
    
    
    url = ['a.com', 1, 2, 3, 4, 5, 6, 7]
    for item in islice(url, 1, None):
        print(item)
    
answered by 15.02.2018 / 00:19
source
-1

To exclude the first element you can do it this way:

url = ['a.com', 1, 2, 3, 4, 5, 6, 7]
for item in url[1:]:
    data ={
        "adSize": {"id":'{}'.format(item) }
        }

All values will be obtained with the exception of the first one ('a.com').

    
answered by 15.02.2018 в 00:19