Python - getting values from 2d arrays

I have a 2d array:

[[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'food'], []]

How do I call a value from it? For example I want to print (name + " " + type) and get

shotgun weapon

I can't find a way to do so. Somehow print list[2][1] outputs nothing, not even errors.

Upvotes: 3

Views: 33678

Answers (4)

Rohit Jain
Rohit Jain

Reputation: 213223

Accessing through index works with any sequence (String, List, Tuple): -

>>> list1 = [[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'food'], []]
>>> list1[1]
['shotgun', 'weapon']
>>> print list1[1][1]
weapon
>>> print ' '.join(list1[1])
shotgun weapon
>>>  

You can use join on the list, to get String out of list..

Upvotes: 3

ronak
ronak

Reputation: 1778

In [80]: [[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'food'], []]
Out[80]: [[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'food'], []]

In [81]: a = [[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'food'], []]

In [82]: a[1]
Out[82]: ['shotgun', 'weapon']

In [83]: a[2][1]
Out[83]: 'weapon'

For getting all the list elements, you should use for loop as below.

In [89]: a
Out[89]: [[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'food'], []]

In [90]: for item in a:
    print " ".join(item)
   ....:     

shotgun weapon
pistol weapon
cheesecake food

Upvotes: 0

sahhhm
sahhhm

Reputation: 5365

>>> mylist = [[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'f
ood'], []]
>>> print mylist[2][1]
weapon

Remember a couple of things,

  1. don't name your list, list... it's a python reserved word
  2. lists start at index 0. so mylist[0] would give []
    similarly, mylist[1][0] would give 'shotgun'
  3. consider alternate data structures like dictionaries.

Upvotes: 6

kreativitea
kreativitea

Reputation: 1791

array = [[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'food'], []]
print " ".join(array[1])

slice into the array with the [1], then join the contents of the array using ' '.join()

Upvotes: 0

Related Questions