Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
basic question isinstance
#1
def sumtree(l):
    tot = 0
    for x in l:
        if not isinstance(x, list):
            tot += x
            print(tot)
        else:
            tot += sumtree(x)
            print('xxx')
    return tot

o = [1, [2, [3, 4], 5], 6, [7, 8]]
I don't understand how this works. It sums the items in the nested nested lists.
I've typed this interactively:
>>> type(o[0])
<class 'int'>
>>> type(o[1])
<class 'list'>
>>> type(o[2])
<class 'int'>
>>> type(o[3])
<class 'list'>

>>> o[1]
[2, [3, 4], 5]
>>> o[0]
1
>>> o[1]
[2, [3, 4], 5]
>>> o[2]
6
>>> o[3]
[7, 8]

if I run it it gives this:

1
2
3
7
xxx
14
xxx
21
7
15
xxx
36
1
3
6
10
10

The for loop seems to step over the first item in each nested list, but why does it do that? It's probably really easy, I've been staring at it for hours. Any help or explanation would be greatly appreciated.
Reply


Messages In This Thread
basic question isinstance - by tames - Nov-22-2020, 12:44 PM
RE: basic question isinstance - by ibreeden - Nov-22-2020, 01:33 PM
RE: basic question isinstance - by tames - Nov-22-2020, 06:34 PM
RE: basic question isinstance - by bowlofred - Nov-22-2020, 06:53 PM
RE: basic question isinstance - by ibreeden - Nov-22-2020, 07:45 PM
RE: basic question isinstance - by tames - Nov-23-2020, 07:20 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Basic Coding Question: Exit Program Command? RockBlok 3 611 Nov-19-2023, 06:31 PM
Last Post: deanhystad
  [solved] Basic question on list matchiing paul18fr 7 1,933 May-02-2022, 01:03 PM
Last Post: DeaD_EyE
  Very basic calculator question BoudewijnFunke 4 1,986 Dec-10-2021, 10:39 AM
Last Post: BoudewijnFunke
  Trying to understand how isinstance(values, collections.Iterable) work. quazirfan 7 4,246 Aug-10-2021, 08:10 AM
Last Post: snippsat
  basic question about tuples and immutability sudonym3 6 2,973 Oct-18-2020, 05:11 PM
Last Post: sudonym3
  Help with isinstance command (very simple code) Laplace12 2 2,029 Jul-30-2020, 05:26 AM
Last Post: Laplace12
  isinstance() always return true for object type check Yoki91 2 2,598 Jul-22-2020, 06:52 PM
Last Post: Yoki91
  Basic Pyhton for Rhino 6 question about variables SaeedSH 1 2,166 Jan-28-2020, 04:33 AM
Last Post: Larz60+
  Basic Beginner question NHeav 4 2,829 Sep-13-2019, 11:43 AM
Last Post: NHeav
  Basic coding question with Python Than999 3 3,146 Jul-17-2019, 04:36 PM
Last Post: jefsummers

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020