0

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:

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)

  • If you want to _slice_ a tuple, you need to use slice notation. You can't specify the indices you want and have those extracted for you using the index notation with vanilla python tuples or lists. – Pranav Hosangadi Jul 11 '22 at 21:14
  • Does this answer your question? [Understanding slicing](https://stackoverflow.com/questions/509211/understanding-slicing) – Pranav Hosangadi Jul 11 '22 at 21:14
  • `row[0:4]` instead of `row[0,1,2,3]` – Barmar Jul 11 '22 at 21:15
  • Note that slicing doesn't let you select non-contiguous slices with irregular steps, such as what you want. In this case, you will need to extract separate slices and then join them like so: `(row[0],) + row[2:5]`. Also note the code you show (`baseAd100.extend(row[0,2,3,4])`) is not the same as your error (`baseAd100.extend(row[0,1,2,3])`). The latter is a contiguous slice, so you can do it simply using slicing – Pranav Hosangadi Jul 11 '22 at 21:16
  • This is probably a better duplicate: https://stackoverflow.com/questions/19128523/accessing-non-consecutive-elements-of-a-list-or-string-in-python – Pranav Hosangadi Jul 11 '22 at 21:19

2 Answers2

0

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.

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
0

thanks @Pranav Hosagadi guide me with your comment, it's not the best, but that's how my code looks

def Ad100():    
    baseAd100 = []    

    for row in val:
        baseAd100.append(str(row[0])+"," + str(row[2:4]))        
    print(baseAd100)