Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

add select values in a tuple with python

does anyone know why that error comes out when trying to add four positions in a variable?
I have tried with only one position and it works for me, but if I try to add more it gives me an error:

My error:

Traceback (most recent call last):
  File "\script.py", line 165, in <module>
    Ad100()
  File "\script.py", line 142, in Ad100
    baseAd100.extend(row[0,2,3,4])
TypeError: tuple indices must be integers or slices, not tuple

My code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def Ad100():
    for rows in pcorte:  ##pcorte es el resultado de una consulta.
        print(rows)
    
    baseAd100 = []
    
    for row in pcorte:
##        llenado.append(row[0]) this way works for me in another function with only the first position
        baseAd100.extend(row[0,2,3,4]) ##in this way it generates an error

    print(baseAd100)

My data:

(‘220002393681’, ‘0171’, ‘823’, ‘S’, 1008, ‘25175’, 997, 547)

>Solution :

List/tuple indexing doesn’t work that with with comma-separated values. You either get one item (row[1]) or a slice of items, e.g. row[1:4] gets items 1 up to but not including 4. See slice() for more details.

There is a method to get non-contiguous indices however:

from operator import itemgetter

baseAd100 = []
row = ('220002393681', '0171', '823', 'S', 1008, '25175', 997, 547)

baseAd100.extend(itemgetter(0,2,3,4)(row))
print(baseAd100)

Output:

['220002393681', '823', 'S', 1008]

itemgetter(0,2,3,4) generates a function that will extract the specified indices
from the argument, then it is passed the row.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading