Peileppe

traversing-lists

Feb 24th, 2014
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.71 KB | None | 0 0
  1. """
  2. from
  3. http://www.codecademy.com/courses/python-beginner-en-2Yy4l/0/8
  4.  
  5. """
  6.  
  7. lists=['Mike',['BMW X3','Audi a8'],['white','black'],[2006,2011]]
  8.  
  9. for item in lists:
  10.     print item
  11.  
  12. print 'Each item printed separately'
  13.  
  14. for item in lists:
  15.     if isinstance(item,list):
  16.         for nested_item in item:
  17.             print nested_item
  18.     else:
  19.         print item
  20.  
  21. print 'Using a recursive method'
  22.  
  23. def traverse(list1):
  24.     for x in list1:
  25.         if isinstance(x,list):
  26.             print '-',
  27.             traverse(x)
  28.         else:
  29.         print x,
  30.     print
  31.     return
  32.  
  33. traverse(lists)
  34.  
  35. print 'Adding to the list'
  36. lists.append('Michael')
  37. lists.append('Brandon')
  38. lists.append('Arthur')
  39. lists.sort()
  40.  
  41. traverse(lists)
Advertisement
Add Comment
Please, Sign In to add comment