1

Fairly new to python here,

I have a python tuple

reportTuple = (('Keith', 'Saturday', 10), ('Jane', 'Monday', 12))

and I want to print the name and the number but only if the value is Saturday. (print elements 0, 2 but only if elements 1 value == Saturday.)

Any ideas how to write to write an if statement to grab them?

3 Answers 3

2

Loop through the array, checking the value of the central element:

for i in reportTuple: # Loop through each element of reportTuple
    if i[1] == "Saturday": # Is the day Saturday?
        print(i[0]) # Print name
        print(i[2]) # Print number

May I ask what the problem was here? Was it the for loop?

Sign up to request clarification or add additional context in comments.

Comments

1

Updated first list with Junapa's modification:

You can do this with a list comprehension.

print(*("{}: {}".format(name,number) for (name, day, number) in reportTuple if day == 'Saturday'))

will print out

Keith 10

If you wanted to save the results of the if statement in a list, then you can do

['{} {}'.format(name, number) for (name, day, number) in reportTuple if day == 'Saturday']

which will return you

['Keith 10']

2 Comments

Well, it's here if he wants it. If not, there are other answer here that he can use. I really liked list comprehensions when I first started learning python so I figured I'll add a list comprehension answer too for him or for the random passerby.
Printing from inside a comprehension is bad form. Comprehensions are functional constructs - people don't expect side effects inside of them. Rather, do something like: print(*("{}: {}".format(name,number) for (name, day, number) in reportTuple if day == 'Saturday'))
0

I'm a very casual Python user so there is almost certainly some magic way to do this far more elegantly than I have, but I just tried this and it worked:

reportTuple = (('Keith', 'Saturday', 10), ('Jane', 'Monday', 12))
for report in reportTuple:
    if report[1] == 'Saturday':
        print(report[0], report[2])

prints

Keith 10

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.