0

Given a list of tuple:

data = [('David', '5239980'), ('Bob', '4562345'), ('Jenny', '2541273')]

What is the easiest way of getting the 2nd element?
E.g. if I want to get the corresponding number value to David or Bob?

1 Answers1

0

I use python list comprehension

[y for x, y in data if (x == 'David' or x == 'Bob')]
sushanth
  • 8,275
  • 3
  • 17
  • 28
  • Could you explain the y for x part? A bit new and having a bit of trouble understanding it –  May 15 '21 at 03:19
  • Let me be a bit more explicit: [y for (x,y) in data if (x=='David' or x == 'Bob')] – Marcos Feijoo May 15 '21 at 03:47
  • from: https://docs.python.org/3/tutorial/datastructures.html – Marcos Feijoo May 15 '21 at 03:50
  • 5.1.3. List Comprehensions List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition. – Marcos Feijoo May 15 '21 at 03:51