Bababo
Bababo

Reputation: 23

How to print last line in a list in Python?

import random

s = []

for i in range(14):
    s.append(random.randint(0,5))

print(s)

how i just print last line in a list? Because Python print me s like this:

[3]

[3, 0]

[3, 0, 3]

[3, 0, 3, 0]

[3, 0, 3, 0, 2]

[3, 0, 3, 0, 2, 3]

[3, 0, 3, 0, 2, 3, 3]

[3, 0, 3, 0, 2, 3, 3, 0]

[3, 0, 3, 0, 2, 3, 3, 0, 5]

[3, 0, 3, 0, 2, 3, 3, 0, 5, 3]

[3, 0, 3, 0, 2, 3, 3, 0, 5, 3, 5]

[3, 0, 3, 0, 2, 3, 3, 0, 5, 3, 5, 5]

[3, 0, 3, 0, 2, 3, 3, 0, 5, 3, 5, 5, 1]

[3, 0, 3, 0, 2, 3, 3, 0, 5, 3, 5, 5, 1, 4] <- this is the only line I want Python print me..

Please help me.

And another question... How i change this program:

for i in s:
   if i < 1:
      print ("It's all good.")
   else:
      print("Not good")

that he will print me "Not good" when at least one of numbers in list is 0?

Upvotes: 0

Views: 2181

Answers (1)

elethan
elethan

Reputation: 16993

You are almost certainly doing this:

import random

s = []

for i in range(14):
    s.append(random.randint(0,5))

    print(s)

Instead, change it to this:

import random

s = []

for i in range(14):
    s.append(random.randint(0,5))

print(s)

In Python, indentation is significant, so if you have your print statement indented inside your for loop, it will be called each time through the loop. If you have it indented at the same level as the for ... it will only execute once after the loop has finished completely.

As to the second question regarding:

for i in s:
   if i < 1:
      print ("It's all good.")
   else:
      print("Not good")

I am not sure where you want to place the logic you are looking for, but you can test if "at least one of numbers in list is 0" with:

if 0 in s:
   print("Not good")

You should have this check outside of your for loop though, because this check need only be performed once per list, rather than once per value in the list.

Upvotes: 1

Related Questions