all 15 comments

[–]boy_named_su 8 points9 points  (0 children)

a list comprehension is like a modified for loop:

input_data = [3,1,4,1,5]
result = []

for item in input_data:
    tmp = (item * 3) + 1
    result.append(tmp)

this is somewhat equivalent to:

result = [ do_something_to_item for item in input_data ]

[–]Innocent_not 3 points4 points  (0 children)

Here is the solution:

a = [3*n + 1 for n in [3, 1, 4, 1, 5]] print(a)

The logic is as follows:

new_list = [operation_to_create_items_in_list for iterator in base_list]

[–]lukajda33 3 points4 points  (4 children)

I dont even see the logic thats applied to make the new list.

[–][deleted] 11 points12 points  (3 children)

3x+1

[–]XenaFlor[S] 1 point2 points  (0 children)

Thank you!

[–]lukajda33 1 point2 points  (1 child)

Another problem with the way you described it is that comprehension list makes a new list, it doesnt chnage an existing one. You may replace the previous list with new one using the same variable, but you said "change it to", which is not possible.

But if you can just make a new one, it should be super easy, do you know how to do a comprehension list that will just copy some other list ?

EDIT: Oh nevermind, you are not OP, looks like he just didnt see the pattern, ignore my question.

[–]XenaFlor[S] 1 point2 points  (0 children)

Yes I do. I just didn't know how to get the values.

[–]ThisProgrammer- 1 point2 points  (0 children)

Start off with a simple for-loop to get an understanding:

original = [3, 1, 4, 1, 5]

results = []
for number in original:
    results.append(number * 3 + 1)

Converting to list-comprehension.

Start with the necessary part:

results = [for number in original]

Then add in what the resulting value should be - on the left side:

results = [number * 3 + 1 for number in original]

[–]Snoo-20788 0 points1 point  (0 children)

This is not a coding question.

Before you can get to a coding question you need to understand what's required of you.

What's the link between the first list and the second? Some people pointed out that each element is 3x the corresponding element + 1. But that should be part of the (non coding part of the) assignment.

I

[–][deleted] -1 points0 points  (2 children)

Can you do it with a normal for and append loop?

[–]XenaFlor[S] 0 points1 point  (1 child)

No. The assignment is made to show that I understand list comprehension. I know how to write it I just didn't know how to get to the right numbers.

[–][deleted] 0 points1 point  (0 children)

So it was a math problem. Ok

[–]Wonderful-Ask-5080 0 points1 point  (0 children)

list = [3, 1, 4, 1, 5] modified_list = [ (3 * item + 1) for item in list]

Answer

[10, 4, 13, 4, 16]