Appending to a List in Python 3 - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Appending to a List in Python 3 (/thread-14452.html) |
Appending to a List in Python 3 - kas_samrari - Nov-30-2018 Hello, I am trying to get the following List output [[2,3,4,5],[3,4,5,6],[4,5,6,7],[5,6,7,8] with a nested For loop. I am able to get the outer list but not the individual lists within the list. Here's my code and the output. Can you please suggest what I need to change to get the desired output and thank you in advance for your help. Kind regards, my_list = [2,3,4,5] lst = [] for i in my_list: for j in range(0,4): lst.append(i+j) print(lst)[2, 3, 4, 5, 3, 4, 5, 6, 4, 5, 6, 7, 5, 6, 7, 8] RE: Appending to a List in Python 3 - ichabod801 - Nov-30-2018 Just like you make lst, you need to make a sub_lst within the for i loop. That's what you append to in the for j loop, and after that loop you append sub_lst to lst.
RE: Appending to a List in Python 3 - kas_samrari - Nov-30-2018 Not sure if I understand. Tried the following but it did not work. Sorry still new to python. my_list = [2,3,4,5] lst = [] sub_lst = [] for i in my_list: sub_lst.append(i) for j in range(0,4): lst.append(sub_lst) print(lst) RE: Appending to a List in Python 3 - ichabod801 - Nov-30-2018 No, like this: for i in my_list: sub_lst = [] for j in range(0, 4): sub_lst.append(i + j) lst.append(sub_lst) RE: Appending to a List in Python 3 - kas_samrari - Nov-30-2018 Thank you. That works perfectly. |