3

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.

2
  • 1
    if you're naming your structure "list", be careful, as list is a reserved word in python. Commented Oct 10, 2012 at 19:02
  • 2
    "I have a 2d array" No you don't, you have ragged nested arrays. Commented Oct 10, 2012 at 19:03

4 Answers 4

6
>>> 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.
Sign up to request clarification or add additional context in comments.

1 Comment

Would use dictionaries if I didn't plan to add other things into these lists. For example if I have ["shotgun", "weapon", "common"] it is no longer a pair :) Thanks anyway
3

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..

1 Comment

Why a down vote?? Do I deserve a comment here from the downvoter??
0
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()

Comments

0
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.