0
noodles = [(‘Samyang’, ‘Korea’, ’50’), (‘Nissin Cup Noodle’, ‘Japan’, ’70’), (‘Jin Mai Lang’, ‘China’, ’40’)]

For example, I only want Nissin Cup Noodle. The output should look like:

Nissin Cup Noodle, Japan, 70

casio_3000
  • 23
  • 5
  • 2
    Try `noodles[1]` to get the second element in the list or `noodles[1][0]` if you want Nissin Cup Noodle only, the first element. – ggorlen Feb 27 '21 at 02:24
  • Does this answer your question? [Accessing a value in a tuple that is in a list](https://stackoverflow.com/questions/4800811/accessing-a-value-in-a-tuple-that-is-in-a-list) – Gino Mempin Feb 27 '21 at 10:25

3 Answers3

0

It sounds like you want to find the index of the a particular entry in a list of tuples based on the first coordinate.

noodles = [('Samyang', 'Korea', '50'), ('Nissin Cup Noodle', 'Japan', '70'), ('Jin Mai Lang', 'China', '40')]
names   = [item[0] for item in noodles]
index   = names.index('Nissin Cup Noodle')

print(noodles[index])
Bobby Ocean
  • 3,120
  • 1
  • 8
  • 15
0

You can use list comprehension and a [0] index...

noodles = [(‘Samyang’, ‘Korea’, ’50’), (‘Nissin Cup Noodle’, ‘Japan’, ’70’), (‘Jin Mai Lang’, ‘China’, ’40’)]
nissan = 'Nissin Cup Noodle'
n_c_n = [(x, y, z) for x, y, z in noodles if x == nissan][0]

or a for loop:

noodles = [(‘Samyang’, ‘Korea’, ’50’), (‘Nissin Cup Noodle’, ‘Japan’, ’70’), (‘Jin Mai Lang’, ‘China’, ’40’)]
nissan = 'Nissin Cup Noodle'
for noodle in noodles:
    if noodle[0] == nissan:
        n_c_n = noodle
        break

But you probably should be using a dict instead if you want to find elements based on a key, you can unpack the tuple with * into a tuple including the key to get your desires tuple of all three:

noodles = {‘Samyang’: (‘Korea’, ’50’), ‘Nissin Cup Noodle’: (‘Japan’, ’70’), ‘Jin Mai Lang’: (‘China’, ’40’)}
nissan = 'Nissin Cup Noodle'
n_c_n = (nissan, *noodles[nissan])
Ryan Laursen
  • 617
  • 4
  • 18
0

You can assign the values in a tuple directly to variables and print them that way too:

for noodle_type, country, num in noodles:
    print(f”{noodle_type}, {country}, {num}”)

Throw an if statement in there if you only want to print out a specific tuple

for noodle_type, country, num in noodles:
    if noodle_type == “whatever”:
        print(f”{noodle_type}, {country}, {num}”)
general-gouda
  • 318
  • 3
  • 9