Member Avatar for cyon

Is there a way to, instead of duplicating code, to either print the desired number of rows from a list (from user input) or print all items in the list?

print_list( input ):

   f = open('pickle.dat', "r")
   L = cPickle.load(f)
   f.close()

   for i in range( input=len(L) ):
      print 'L[i] = ', L[i]

It doesn't seem like I can set input=len(L) in the for loop or in the method header. Ideally, I'm trying to attain the following behavior:


>>> L = [ 'A', 'B', 'C', 'D', 'E' ]
>>> do_something (3)
L[0] = A
L[1] = B
L[2] = C

>> do_something()
L[0] = A
L[1] = B
L[2] = C
L[3] = D
L[4] = E

Also, if desired_items > len(L), I'd like to default to all items in the list as well:

>> do_something(100)
L[0] = A
L[1] = B
L[2] = C
L[3] = D
L[4] = E

Thanks for any help!

print_list( input ): ## ??? you can not call input in parameter list 

   f = open('pickle.dat', "r")
   L = cPickle.load(f)
   f.close()

   for i in range(len(L) ): ## you mean len(L) don't you
      print 'L[i] = ', L[i]
>>> def do_something(a=None):
	if not a: a=len(L)
	a=min(len(L),a)
	if a:
		for i in enumerate(L[:a]):
			print "L[%i]=%s" % i

			
>>> do_something()
L[0]=A
L[1]=B
L[2]=C
L[3]=D
L[4]=E
>>> do_something(3)
L[0]=A
L[1]=B
L[2]=C
>>> do_something(100)
L[0]=A
L[1]=B
L[2]=C
L[3]=D
L[4]=E
>>>

Here's a functional solution:

def list_disp(lst,num = -1,lname = "L"):
    i = 0
    result = ""
    try:
        while num:
            num -= 1
            result += "{0}[{1}] = {2}\n".format(lname,
                                              i,
                                              lst[i])
            i += 1
        return result
    except:
        return result

print list_disp([1,2,3,4,5],9)

print list_disp([1,2,3,4,5],3,"LIST")

To get text from user

## ask user parameter for use
what=raw_input('Give the parameter')
print "The result is ",myfunc(what)

If you need number you must use functions to get for example number.
This code is for Python 2 (as was your code, print not function)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.