Python Forum
Appending to a List in Python 3
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Appending to a List in Python 3
#1
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]
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
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)
Reply
#4
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)
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#5
Thank you. That works perfectly.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Time.sleep: stop appending item to the list if time is early quest 0 1,868 Apr-13-2021, 11:44 AM
Last Post: quest
  Reading and appending list MrSwiss 1 1,720 Mar-01-2021, 09:01 AM
Last Post: Serafim
  Appending list Trouble Big Time Milfredo 7 3,088 Oct-01-2020, 02:59 AM
Last Post: Milfredo
  Appending to list of list in For loop nico_mnbl 2 2,349 Sep-25-2020, 04:09 PM
Last Post: nico_mnbl
  appending list of list glennford49 2 2,134 Mar-29-2020, 09:33 AM
Last Post: ibreeden
  Appending to list not working and causing a infinite loop eiger23 8 3,963 Oct-10-2019, 03:41 PM
Last Post: eiger23
  Appending a list in a class from a callback function snizbatch 5 3,709 Sep-01-2019, 06:27 AM
Last Post: snizbatch
  appending list items to other lists clarablanes 4 2,841 Dec-08-2018, 02:15 PM
Last Post: clarablanes
  trouble while appending list in for loop py_learner 1 2,843 May-28-2018, 01:55 AM
Last Post: scidam
  Unexpected behavior appending to a List of Dictionaries Nomad 2 2,724 Apr-03-2018, 04:22 AM
Last Post: Nomad

Forum Jump:

User Panel Messages

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