33

I have a list

list = [['vegas','London'],['US','UK']]

How to access each element of this list?

CharlesB
  • 86,532
  • 28
  • 194
  • 218
user1389673
  • 365
  • 1
  • 3
  • 6
  • 10
    This is an extremely basic question, one that leads me to believe you urgently need to read the [Python tutorial](http://docs.python.org/tutorial/). For example, it seems your data structure does not make much sense, a dictionary might be a better choice: `cities = {"Vegas": "US", "London": "UK"}`. – Tim Pietzcker May 16 '12 at 06:44
  • Also, you are overriding the default `list`. Take a look [here](https://docs.python.org/3/tutorial/datastructures.html) and try not to redefine the default data-structures (`list`, `set`, `dict`, `tuple`) or anything in the global `dir()` that does not belong to you. – Countour-Integral Feb 15 '21 at 06:44

5 Answers5

38

I'd start by not calling it list, since that's the name of the constructor for Python's built in list type.

But once you've renamed it to cities or something, you'd do:

print(cities[0][0], cities[1][0])
print(cities[0][1], cities[1][1])
sblom
  • 26,911
  • 4
  • 71
  • 95
7

It's simple

y = [['vegas','London'],['US','UK']]

for x in y:
    for a in x:
        print(a)
AutomationNerd
  • 406
  • 1
  • 5
  • 12
2

Tried list[:][0] to show all first member for each list inside list is not working. Result will be the same as list[0][:].

So i use list comprehension like this:

print([i[0] 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.

anugrahandi
  • 461
  • 4
  • 4
1

Learn python the hard way ex 34

try this

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])
Mel
  • 5,837
  • 10
  • 37
  • 42
0

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)
Kajal
  • 709
  • 8
  • 27