skip to Main Content

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


  1. You can use zip to iterate collectively through parallel lists.

    for name, age, job, salary, bonus in zip(names, ages, jobs, salaries, bonuses):
        print ("Employee %s" % name)
        print ("is %s years old" % age)
        print (", their job title is %s" % job)
        print (" and they make %s annually" % salary)
        print ("Their 2017 bonus will be %s." % bonus)
    

    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:

    for name, age, job, salary, bonus in zip(names, ages, jobs, salaries, bonuses):
        print ("Employee %s is %s years old. Their job title is %s, and "
               "they make %s annually. Their 2017 bonus will be %s."
               %(name, age, job, salary, bonus))
    
    Login or Signup to reply.
  2. zip these together and, ideally, use a format string for cutting down the overall lines since they all use the same format:

    emps = zip(names, ages, jobs, salaries, bonuses)
    fmt = ("Employee {} is {} years old, their job " 
           "title is {} and they make {} annually. " 
           "Their 2017 bonus will be {}.")
    for emp in emps:
        print(fmt.format(*emp))
    

    Tweak the format in fmt accordingly.

    Login or Signup to reply.
  3. You could also just access the lists by index if you know for sure that all lists have the same length.

    for i in range(len(names)):
        print(names[i], ages[i], jobs[i], salaries[i], bonuses[i])
    

    I personally don’t think this makes the code any less readable compared to using zip.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search