elliot alderson
elliot alderson

Reputation: 11

how to print first and last value of one list in another list

I want to print first and last value of list a in b. I'm a newbie in python

b = []
a = [5, 10, 15, 20, 25]

  for i in a:
        if i == 0:
          b.append(a[i])
         if i == len(a)-1:
           b.append(a[i])

Expected Result

print(b)
[5,25]

Upvotes: 1

Views: 102

Answers (2)

CarlosMorente
CarlosMorente

Reputation: 918

In Python you don't need to be calculating the length of a list. If you want to add the first and the last elements of a list into another, you only have to do this:

a = [5, 10, 15, 20, 25]
b = [a[0],a[-1]]
print(b)

Upvotes: 1

Nihal
Nihal

Reputation: 5324

a = [5, 10, 15, 20, 25]

print(a[0])
print(a[-1])

Upvotes: 1

Related Questions