atm atm
atm atm

Reputation: 69

list within a list

I'm working on this problem, but I cannot figure out the second part. I tried using reverse list but it did not work out how I planned it.

Given a list L (e.g. [1,2,3,4]), write a program that generates the following nested lists:

  1. L1 = [[1],[1,2],[1,2,3],[1,2,3,4]],
  2. L2 = [[4],[3,4],[2,3,4],[1,2,3,4]].

My code that I have so far:

mylist=[,1,2,3,4] 
print("Orginal list L=",mylist) 
n=len(mylist) 
l1=[] 
l2=[] 


for x in range(1,n+1,1):
    l1.append(mylist[0:x]) 
print("L1=",l1) #prints final product of l1


mylist.reverse() #this is where i get messed up
for x in range(1,n+1,1): 
    l2.append(mylist[0:x]) 
print("L2=",l2) 

Upvotes: 1

Views: 115

Answers (4)

Need4Steed
Need4Steed

Reputation: 2180

lst = [1,2,3,4]
[lst[0:i] for i in range(1,5)]
[lst[-i:] for i in range(1,5)]

Upvotes: 1

nneonneo
nneonneo

Reputation: 179422

Man, I love list comprehension.

L1 = [L[:i+1] for i in xrange(len(L))]
L2 = [L[-i-1:] for i in xrange(len(L))]

You can think of list comprehension as an easy way to build a list. Usually, if you see yourself doing for x in y: ... list.append(z), a list comprehension may be a shorter and more elegant solution.

Upvotes: 1

Thierry J
Thierry J

Reputation: 2189

You can use negative indexes in python:

mylist[-1] -> 4

Given that, this will work:

mylist=[1,2,3,4] 
print("Orginal list L=", mylist)
n=len(mylist) 
l1=[] 
l2=[] 

for i in range(1, n+1):
    l1.append(mylist[0:i])
    l2.append(mylist[-i:])
print("L1=", l1)
print("L2=", l2)

Upvotes: 2

Joran Beasley
Joran Beasley

Reputation: 113988

dont reverse your list and change second loop

for x in range(n-1,-1,-1): 
    l2.append(mylist[x:]) 

Upvotes: 0

Related Questions