1

Am trying to print elements of index 1 like 4994 2993 100 20.5 from my tuple but it print ('dan', '2993').

b = (("ben","4994"),("dan","2993"),("Hans",100),("Frank",20.5))


print(b[1])

Have searched on this site and none of the answer provided gives me clue to solve this.

LAS
  • 179
  • 4
  • 14

3 Answers3

2

You can use unpacking in a list comprehension:

b = (("ben","4994"),("dan","2993"),("Hans",100),("Frank",20.5))
new_b = [i for _, i in b]

Output:

['4994', '2993', 100, 20.5]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
2

Another list comprehension way:

b = (("ben","4994"),("dan","2993"),("Hans",100),("Frank",20.5))
new_b = [i[1] for i in b]
# ['4994', '2993', 100, 20.5]
Austin
  • 25,759
  • 4
  • 25
  • 48
0
b = (("ben","4994"),("dan","2993"),("Hans",100),("Frank",20.5))

for item in b:
    print(item[1])

In this case you are trying to access the second element of a two-items tuple. Using slicing would be:

>>> b[0][1]

and you will get as output>

>>> '4994'

If you put this tuple into a for loop, the first element (item in my code) would be: ("ben","4994") and when you print(item[1]) you are having access to the second level of slicing, that is: '4994' in the first running of the loop and so on.

lpozo
  • 598
  • 2
  • 9
  • While this code may answer the question, providing additional context regarding **how** and/or **why** it solves the problem would improve the answer's long-term value. – Alexander Mar 28 '18 at 15:33