Sasan
Sasan

Reputation: 17

List in a list recognition in python

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)

Upvotes: 1

Views: 251

Answers (2)

jonrsharpe
jonrsharpe

Reputation: 122126

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

Upvotes: 2

RageCage
RageCage

Reputation: 740

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

Upvotes: 0

Related Questions