Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
make a simple list
#1
i try to make a simple list f.e. x=n**2+1
code is
x=[]
for n in range (4):
    y=n**2+1
    x.append(y)
    print (x)
then it prints all...
Output:
[1] [1, 2] [1, 2, 5] [1, 2, 5, 10]
i need only the last...
any suggestions?
Reply
#2
line#5 must be out of the loop. unindent it one level.

x=[]
for n in range(4):
    y = n ** 2 + 1
    x.append(y)
print(x)
or you can use list comprehension
x = [n ** 2 + 1 for n in range(4)]
print(x)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
found it

instead of
>>>print (x)

just

>>>x
Reply
#4
(Jul-20-2018, 12:24 PM)larri Wrote: found it

instead of
>>>print (x)

just

>>>x
this will work only in python interactive console, but not in script
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Why do I have to repeat items in list slices in order to make this work? Pythonica 7 1,320 May-22-2023, 10:39 PM
Last Post: ICanIBB
  help me to make my password list in python >>> Oktay34riza 0 574 Dec-23-2022, 12:38 PM
Last Post: Oktay34riza
  How would you (as an python expert) make this code more efficient/simple coder_sw99 3 1,786 Feb-21-2022, 10:52 AM
Last Post: Gribouillis
  Make Groups with the List Elements quest 2 1,963 Jul-11-2021, 09:58 AM
Last Post: perfringo
Question How to make a 3D List of Excel Spreadsheets? chatguy 4 2,737 Jan-24-2021, 05:24 AM
Last Post: buran
  Undo interation to make a single list? DustinKlent 2 2,161 Nov-29-2020, 03:41 AM
Last Post: DustinKlent
  How to make global list inside function CHANKC 6 3,074 Nov-26-2020, 08:05 AM
Last Post: CHANKC
  How do i make a new lists out of an list ozezn1 1 1,683 Oct-28-2020, 10:19 PM
Last Post: Gribouillis
  Make list of dates between today back to n days Mekala 3 2,373 Oct-03-2020, 01:01 PM
Last Post: ibreeden
  How to make a list of values from a dictionary list? faryad13 2 2,059 Sep-03-2020, 03:45 PM
Last Post: faryad13

Forum Jump:

User Panel Messages

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