0

How do you add two lists together using nested loop?

I want it like the list below. How is this index out of range? first = [1, 8, 27, 64, 125] second = [1, 8, 27, 64, 125] def sum_cube(): total_cubes = [] for i in range(len(first)): for j in range(len(second)): total = first[i] + second[j] total_cubes.append(total) second.remove(second[j])

4th Jun 2021, 9:29 AM
Ash 07
Ash 07 - avatar
6 Answers
+ 1
What is the expected result in <total_cubes>?
4th Jun 2021, 10:26 AM
Ipang
+ 1
Like this? [ 2, 16, 54, 128, 250 ] For this you can use list comprehension combined with use of zip() function. If it's not what you expected, then an example result may help me understand.
4th Jun 2021, 11:45 AM
Ipang
0
first.extend(second)
4th Jun 2021, 9:56 AM
Yash Wable 🇼🇳
Yash Wable 🇼🇳 - avatar
0
Two cubes added together that is put into a list
4th Jun 2021, 11:01 AM
Ash 07
Ash 07 - avatar
0
[2, 9, 28, 16, 35, 28, 54] the sum of two cubes with none repeated
4th Jun 2021, 3:44 PM
Ash 07
Ash 07 - avatar
0
""" what do you mean by "with none repeated", as your list before contains twice the number 28? """ def sum_cube(n): cubes = [*map(lambda x: x*x*x,range(1,n+1))] print(cubes) res = [] for v in cubes: for u in cubes: """ # uncomment block to not repeat # and comment last line instead u += v if not u in res: res.append(u) """ res.append(u+v) return res print(sum_cube(3)) """ output without changing comment: [2, 9, 28, 16, 35, 28, 54] with uncomment (and comment last function line): [2, 9, 28, 16, 35, 54] """
4th Jun 2021, 4:04 PM
visph
visph - avatar