If this is a duplicate question, I am sorry. I have spent a good hour trying to find the answer and tested a couple theories with no success. Without posting my whole code I’m working on, I’ll just post the snippet.
Basically I need to print these for loop statements all into one line to run for each employee.
i.e. ‘Employee Sam is 31 years old, their job title is Data Analyst and they make $90,000 annually. Their 2017 bonus will be $2,700.”
# Employee List
names = ['Sam', 'Chris', 'Jose', 'Luis', 'Ahmad']
ages = ['31', '34', '30', '28', '25']
jobs = ['Data Analyst', 'SEO Python Genius', 'Data Analyst', 'Interchange
Analyst', 'Data Analyst']
salaries = ['$90,000', '$120,000', '$95,000', '$92,000', '$90,000']
bonuses = ['$2,700', '$3,600', '$2,850', '$2,750', '$2,700']
# this for-loop goes through name list
for name in names:
print ("Employee %s" % name)
for age in ages:
print ("is %s" % age, "years old")
for job in jobs:
print (", their job title is %s" % job)
for salary in salaries:
print (" and they make %s" % salary, "annually.")
for bonus in bonuses:
print ("Their 2017 bonus will be %s." % salary)
3
Answers
You can use
zip
to iterate collectively through parallel lists.This will still each part of the message on a separate line, because they are separate print statements. Instead, you could combine them into one
print
:zip
these together and, ideally, use a format string for cutting down the overall lines since they all use the same format:Tweak the format in
fmt
accordingly.You could also just access the lists by index if you know for sure that all lists have the same length.
I personally don’t think this makes the code any less readable compared to using
zip
.