1

mysql has output a list of tuples of the form

a=[("1","2","3"),("4","5","6"),("7","8","9")]

I want a list of tuples of the form

c=[("2","3"),("5","6"),("8","9")]

i.e. the last two elements of each tuple, so i can put that into a my sql executemany command and get the next piece of data.

my intuition was that i could get the desired matrix with the command

c=[for b in a: b[1:]]

but python, doesn't like that. Why doesn't that work, and what's the most pythonic way of getting the desired list of tuples?

Red
  • 26,798
  • 7
  • 36
  • 58
Abijah
  • 512
  • 4
  • 17

4 Answers4

5

You have your syntax slightly wrong, but have taken the right approach.

c = [b[1:] for b in a]
Adam Smith
  • 52,157
  • 12
  • 73
  • 112
4

You'll want to slice each item in a:

>>> a = [("1","2","3"),("4","5","6"),("7","8","9")]
>>> [i[1:] for i in a]
[('2', '3'), ('5', '6'), ('8', '9')]
AKX
  • 152,115
  • 15
  • 115
  • 172
4

You can go through like this, here for loops will go at end:

a=[(1,2,3),(4,5,6),(7,8,9)]
c=[b[1:] for b in a]
print(c)
Wasif
  • 14,755
  • 3
  • 14
  • 34
2

Since, you want the last two elements of each tuple, using the slice [1:] (like in the other answers) won't work when the number of elements in each tuple is not 3.

Instead, use a list comprehension with the negative slice of [:-2]:

a = [("1","2","3"),("4","5","6"),("7","8","9")]
a = [t[-2:] for t in a]
print(a)

Output:

[('2', '3'), ('5', '6'), ('8', '9')]
Red
  • 26,798
  • 7
  • 36
  • 58