Each Answer to this Q is separated by one/two green lines.
I have a list
list = [['vegas','London'],['US','UK']]
How to access each element of this list?
I’d start by not calling it
list, since that’s the name of the constructor for Python’s built in
But once you’ve renamed it to
cities or something, you’d do:
print(cities, cities) print(cities, cities)
y = [['vegas','London'],['US','UK']] for x in y: for a in x: print(a)
Learn python the hard way ex 34
animals = ['bear' , 'python' , 'peacock', 'kangaroo' , 'whale' , 'platypus'] # print "The first (1st) animal is at 0 and is a bear." for i in range(len(animals)): print "The %d animal is at %d and is a %s" % (i+1 ,i, animals[i]) # "The animal at 0 is the 1st animal and is a bear." for i in range(len(animals)): print "The animal at %d is the %d and is a %s " % (i, i+1, animals[i])
list[:] to show all first member for each list inside list is not working. Result will be the same as
So i use list comprehension like this:
print([i for i in list])
which return first element value for each list inside list.
PS: I use variable
list as it is the name used in the question. I will not use this as a variable name since it is the basic function
list() in Python.
Recursive solution to print all items in a list:
def printItems(l): for i in l: if isinstance(i,list): printItems(i) else: print i l = [['vegas','London'],['US','UK']] printItems(l)