John Doee
John Doee

Reputation: 217

How to print integers into list form

I am kind of new to python. I am trying to print only the integers in a list divisible by 5. Which I have done. But I want the output to be a list, not only the integers.

My Code:

list = [2,4,5,10,12]
for x in list:
if not x % 5 == 0:
    print (x)

I want the output to look like: [2,4,12]

But intsead it looks like:

2,

4,

12

Is there any commands to print the "x" items into a list? Like print(list[x])?

Upvotes: 0

Views: 1293

Answers (3)

bit_flip
bit_flip

Reputation: 171

The OP, using the following numbers [2,4,5,10,12] is "trying to print only the integers in a list divisible by 5. I want the output to look like: [2,4,12]"

Generally, "numbers divisible by 5" are capable of being divided by 5 without a remainder. From the given list the output would be [5,10]

data = [2, 4, 5, 10, 12]

# Print numbers evenly divisible by 5.
print([i for i in data if i % 5 == 0])

[5, 10]

From the output provided by the OP, he's looking for numbers where there is a remainder after dividing by 5.

data = [2, 4, 5, 10, 12]

# Print numbers not evenly divisible by 5.
print([i for i in data if i % 5])

[2, 4, 12]

Upvotes: 0

Craig
Craig

Reputation: 4855

You need to collect your answers in a new list and then print that list. You can do this by creating an empty list and using the .append() method to add items to that list.

my_list = [2,4,5,10,12]
answers = []
for x in my_list:
    if not x % 5 == 0:
        answers.append(x)
print(answers)

A list comprehension is another option. A list comprehension is a powerful shortcut that creates the second list for you automatically.

For this problem, you could use:

my_list = [2,4,5,10,12]
answers = [x for x in my_list if x%5 != 0]
print(answers)

which accomplishes the same thing as the for loop in fewer lines. In this case, you may have to use the for version, but you may want to use a comprehension in the future.

Upvotes: 1

Wazaki
Wazaki

Reputation: 899

This is how I achieved that. I hope it helps:

list1 = [2,4,5,10,12]
list2 = []
for x in list1:
    if not x % 5 == 0:
        list2.append(x)
print(list2)

Upvotes: 1

Related Questions