1

What is the difference of this two list in python:

list1 = [1,2,3,4,5,6,7,8,9]
list2 = [[[[1,2,3,4,5,6,7,8,9]]]]

When I use type(list1) and type(list2), all come with list , but when I try to make some deal such as:

Using list1:

new_total=[]
for i in range(0,len(list1),3):
    b=list1[i:i+3]
    print(len(b))

output:

9
6
3

Using list2:

for i in range(0,len(list2),3):
    b=list2[i:i+3]
    print(len(b))

output:

1
2
  • 2
    The second is a list of list of list of list, that's why you are getting another list as the 0th element of your list. Commented Jun 26, 2018 at 6:17
  • Actually your first output is wrong; it should be: 3 3 3. Commented Jun 26, 2018 at 6:24

3 Answers 3

2

Well the elements within list 2 are the first element of the list within a list within a list.

So they are both of type list, however in the first you are printing the length of three indexed values hence 3.

In the second for loop you are printing the length of the inner list within a list, that only has one element in it (another list, which contains a list that contains the list of numbers within that)

Basically you have embedded the list of numbers 4 fold as the first element within the original list

Sign up to request clarification or add additional context in comments.

Comments

1

replying for only to clarify these reponses , just to help you to understand (as a friend) , i'll give some exemples, that may help you:

list1 = [1,2,3,4,5,6,7,8,9]
list2 = [[[[1,2,3,4,5,6,7,8,9]]]]
print (list2[0][0][0][0])
print (list2[0][0][0])
print (list2[0][0])
print (list2[0])
print (list2)

Output:

1
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[[1, 2, 3, 4, 5, 6, 7, 8, 9]]
[[[1, 2, 3, 4, 5, 6, 7, 8, 9]]]
[[[[1, 2, 3, 4, 5, 6, 7, 8, 9]]]]

I hope that's clear. Good luck!

2 Comments

Puis, you can do the same to : print (len(list2[0][0][0])) ... etc. To see 2nd one is 9 and rest are 1 while 1st one will give an error cuz its a integer and len function isn't defined for it.
Thanks,got it. That's helpful.
0
list1 = [1,2,3,4,5,6,7,8,9]
list2 = [[[[1,2,3,4,5,6,7,8,9]]]]

list1 is a list.

list2 is a list of list of list of list.

len(list1) #will get you 9.
len(list2) #will get you 1.

You will either have to iterate into the final list inside list2 or somehow flatten it into a one dimensional list. Hope this helps point you in the right direction without directly giving out the answer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.