Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
List
#1
Can someone help me? I have a list = [[10,20], [30,40],[50,60]]

I have to generate the sum of the list elements p.e: (10+20), (30+40), (50+60). Then I have to add the new results into the list above.
Output should be: [[10,20,30], [30,40,70], [50,60,110]]

After that I have to convert the list into a tuple.

How can I solve this? Annotation: I´m a total beginner. I tried to use the sum() function - Didn´t work. Furthermore I have no idea how I could use a loop in this task. Huh

Thank you in advance!
Reply
#2
Show us the code you have tried. Note that you just need to loop over the list, which will give you the sub-lists. Just append the sum of the sub-list to each sub-list.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
First I tried it this way:

list = [[10,20],[30,40],[50,60]]

list[0].append(30)
list[1].append(70)
list[2].append(110)

print (list)

Output: [[10, 20, 30], [30, 40, 70], [50, 60, 110]]

The solution is correct, but not the way to solve it. Furthermore I rly don´t knot how I can use the loop for this task.
Reply
#4
try this loop:

for sub_list in my_list:
    print(sub_list)
And think how that could be used in the problem. And don't name your list list, that's a word with meaning in Python. Changing what it means can mess up other code.

Also think about list[0].append(30). You want to replace the 30. What should it be replaced with?

And please use python and output tags when posting code and results. Here are instructions on how to do it.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#5
Adding to ichabod801's suggestion:

you can add the contents of your sublist like this:
sum(sub_list)
so loop, sum, append
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020