PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, May 13, 2022

[FIXED] how to display the output of a for loop as a list and then append it to another list?

 May 13, 2022     append, list, loops, python     No comments   

Issue

I've found and appended the divisors of numbers in a range into a list and now I have the output: [1, 1, 1, 2, 1, 1, 2, 3, 1, 1, 2, 4, 1, 3, 1, 2, 5] but I need each sequence of divisors as a separated list such [[1],[1], [1], [1, 2], [1], [1, 2, 3], [1], [1, 2, 4], [1, 3], [1, 2, 5]]. How can I achieve this output? my code so far is below:

lis1=[1]
lis2=[]
s=0
for i in range(2, 11):
    lis1.append(i)
    for j in range(1,i):
        if i % j == 0:
            lis2.append(j)

print(lis1)
print(lis2)

Solution

@spill1 already gave the exact answer I would have written, so just for the sake of variety, here's a way you can do it in one line with nested list comprehensions:

[[y for y in range(1, x) if not x % y] for x in range(2, 11)]


Answered By - StardustGogeta
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

1,214,522

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © 2025 PHPFixing