Question

I'm new in python and I have been learning list and dictionaries recently. I'm stuck in an exercise of lists inside another list (in other words, nested lists).

The idea of this program is to take these two lists:

listOne = list(range(1, 100))

listTwo = list(range(99, 0, -1))

and the program should take, for example, the element 0 of the first list and the element 0 of the second list and so on with the following numbers, the answer should be like:

[[1,99],[2,98],[3,97], .....]

This is what I have typed so far:

listOne = list(range(1, 100))
listTwo = list(range(99, 0, -1))
listThree = []

for x in listOne:
    for y in listTwo:
        listThree.append((x, y))

print(listThree)

However, when I run this program, the computer prints a huge and crazy result that takes around 5 seconds to print the result. I want this program to be the most simple as possible since I haven't learned a lot. If you have any suggestions for working with nested lists more efficiently, please let me know. Thank you!

Was it helpful?

Solution

Your loop tries to enumerate every possible combination of elements in listOne and listTwo. Does the following achieve what you want(in python 2.7.6)?

for index in range(len(listOne)): listThree.append((listOne[index],listTwo[index]))

OTHER TIPS

The easiest way to get the output list you're looking for is to use the zip function:

listOne = list(range(1, 100))
listTwo = list(range(99, 0, -1))

print(zip(listOne, listTwo))

Much easier would be to use list comprehension here:

listOne = list(range(1,100))
listTwo = list(reversed(listOne))
listThree = [[x, 100-x] for x in range(1,100)]

or with zip:

listThree = zip(listOne, listTwo) # tuples are results
listThree = zip(listOne, reversed(listOne)) # tuples are results
listThree = map(list, zip(listOne, listTwo)) # list are results
listThree = [[a,b] for a,b in zip(listOne, listTwo)] # list are results

if you don't need two first lists, you can chain this up for one-liner:

listThree = list(map(list, zip(range(1,100), reversed(range(1,100))))) # result is list of lists
listThree =  list(zip(range(1,100), reversed(range(1,100)))) # result is list of tuples
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top