1

I wrote this simple code to realize if members in a list are list itself and if so print the members. I would love to hear if it is the right way to approach or not:

listt = ['spam!', 1, ['B', 'R', 'P'], [1 , 2, 3]]
leng= range(len(listt))

def listPrint(listt, leng):
    for i in leng:

        print "List member",i,":"
        list1 = listt[i]
        print listt[i]


        if isinstance(listt[i], list):
            leng2 = range(len(listt[i]))
            print 'and the members are:'
            for e in leng2:
                print list1[e], '\n'

        else:
            print '\n'

listPrint(listt,leng)
Sasan
  • 17
  • 8

2 Answers2

2

Here is a much neater version, with some in-line comments:

def list_print(lst): # PEP-8 function name
    """Print the list, including sub-lists, item by item.""" # docstring
    for index, item in enumerate(lst): # use enumerate to get item and index
        print "List member {0}: ".format(index) # use str.format to create output
        print repr(item) # repr gives e.g. quotes around strings
        if isinstance(item, list):
            print "and the members are:"
            for subitem in item: # iterate directly over list
                print repr(subitem)
        print "" # blank line between items

A few notes:

  • Python has an official style guide, that you should read and at least consider following;
  • Include documentation, particularly where your function does something surprising (like expecting leng to be a range, not just the integer length);
  • Python includes plenty of functionality for iterating over things, for i in range(len(...)) is very rarely the right answer:
    • enumerate, zip and plain old for x in y are much easier to read and use;
    • At the very least, you should have moved range(len(listt)) inside the function, don't pass two pieces of information you can get from the same object; and
  • Using str.format is neater and more Pythonic than passing multiple arguments to print.

In use:

>>> list_print(['spam!', 1, ['B', 'R', 'P'], [1 , 2, 3]])
List member 0: 
'spam!'

List member 1: 
1

List member 2: 
['B', 'R', 'P']
and the members are:
'B'
'R'
'P'

List member 3: 
[1, 2, 3]
and the members are:
1
2
3
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • i see your point. by "Pythonic" do you mean more "object-oriented" ? i think i need time to digest all of this :) – Sasan Jul 30 '14 at 17:48
  • @Sasan see e.g. [What does Pythonic mean?](http://stackoverflow.com/q/25011078/3001761) – jonrsharpe Jul 30 '14 at 17:49
  • i went over the built in functions you used. indeed very useful! but since I am very new to coding I would rather to try to write the code without using the functions once then after I understand the logic, I use the functions to simplify the code! do you agree? – Sasan Jul 30 '14 at 20:31
  • @Sasan it's up to you, but the rich standard library is a major benefit of python and you should get to grips with it – jonrsharpe Jul 30 '14 at 20:32
0

Python's for loops actually iterate through items in the same way as a foreach loop would in other languages. This, in tandem with Python's built-in type() function, can really simplify the process.

def listPrint(listt):
    i=0  #for counting the members of the list
    for elem in listt:  #Now you can use each element directly
        print "List member",i,":"
        print elem
        if type(elem) is list:
            print " and the members are: "
            for thing in elem:
                print thing
        print '\n'
        i+=1

EDIT:

Here is a version using isinstance(), if that is what you would prefer using. I always use type() for this sort of thing so it was my first thought, but I suppose I should have incorporated what you were using in the first place.

def listPrint(listt):
    i=0  #for counting the members of the list
    for elem in listt:  #Now you can use each element directly
        print "List member",i,":"
        print elem
        if isinstance(elem, list):
            print " and the members are: "
            for thing in elem:
                print thing
        print '\n'
        i+=1
RageCage
  • 722
  • 2
  • 6
  • 19
  • `isinstance` is fine - better than `type`, as it handles inheritance - and you should really test equality (`==`) not identity (`is`). – jonrsharpe Jul 30 '14 at 17:23
  • Does it really make any difference in the case of type()? It works just fine. – RageCage Jul 30 '14 at 17:31
  • For both of my points - your current code will work, but could be better. – jonrsharpe Jul 30 '14 at 17:33
  • Sorry, "work" was the wrong word. I mean will it actually affect the performance of the code? isinstance() and type() should be pretty much interchangeable in a case this basic, and comparing identity vs. equality shouldn't matter in this case because they both evaluate to True anyway. What makes identity worse than equality in this case? – RageCage Jul 30 '14 at 17:38
  • Not in this case. `type` will work here, but why use it when *the OP already had something better?* [Apparently](http://stackoverflow.com/a/2225066/3001761) `list` etc. are singletons, so `is` was correct - sorry about that. – jonrsharpe Jul 30 '14 at 17:43