Python - getting values from 2d arrays

25,829

Solution 1

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

Solution 2

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

Share:
25,829
Борис Цейтлин
Author by

Борис Цейтлин

Updated on October 11, 2020

Comments

  • Борис Цейтлин
    Борис Цейтлин over 3 years

    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.

  • Борис Цейтлин
    Борис Цейтлин over 11 years
    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
  • Rohit Jain
    Rohit Jain over 11 years
    Why a down vote?? Do I deserve a comment here from the downvoter??