Correcting output of print w/ lists

Observe this piece of code:

import random
heights = [[‘Jenny’, 61], [‘Alexus’, 70], [‘Sam’, 67], [‘Grace’, 64]]

The output makes [‘Sam’, 67]

I want the ouput to return only Sam 67, how would I do this without the brackets or anything else. I have already tried doing print(random.choice(str(heights))) which obviously did not work.
Can anyone help with how to make this ouput different while still using a list?

Build a string yourself from the smaller things you’ve got

I know I can do this, but do I have to, is there no other way still making a list?

what does that mean?

building a string based on things that you got from a list doesn’t mean you need to stop using a list, not sure what you mean by that

As in still using a list for my variable, not changing my variable, only the way it prints

In that case please show me what you mean

choose one of the name-age pairs, convert the age to string and concatenate them with a space in-between
there’s no need to change your heights variable for that

1 Like

Haha, that was too simple. Thank you.

You could define a relation between a pair and a string representation of a pair.

That’s what a function is, a relation from one value to another.

Given such a function and a list of pairs, you could then obtain a list of string representations of those pairs.

Now you’ve got multiple strings, which could potentially be building blocks of a larger strings, perhaps a summary of them all. You could for example concatenate them all, perhaps you’d want something in-between them like a newline and/or some other separator.

If you have many things and want to put something between each thing, then that would be another relation from some input to some output, so you could for example:

intersperse(['1', '2', '3'], ',')

(intersperse isn’t a built-in function)

to obtain:

['1', ',', '2', ',', '3']

to then be concatenated into


you might only be interested in writing out one pair, but perhaps this gives you an idea of how you might move data around to get to where you want

1 Like

Thank you, I appreciate your help

This topic was automatically closed 18 hours after the last reply. New replies are no longer allowed.