AlexPham
AlexPham

Reputation: 321

Naming elements in Python list

In PHP, I can named element in a list like:

<?php
    list($name,$address,$home) = array("Alex","Taiwan","Vietnam");
    echo $address."\n";
?>

Output: Taiwan

Can it work the same in Python? I am tired of doing like:

list = ["Alex","Taiwan","Vietnam"]
print list[1] 

Upvotes: 0

Views: 15361

Answers (4)

nephlm
nephlm

Reputation: 553

It sounds like you actually want a dictionary:

d = {'name': 'Alex', 'address': 'Taiwan', 'home': 'Vietnam'}
print d['address']

If you need the ordered list you can make an ordered dict and call values() on it.

import collections
d = collections.OrderedDict({'name': 'Alex', 'address': 'Taiwan', 'home': 'Vietnam'})
d.values()

Upvotes: 1

Byte Commander
Byte Commander

Reputation: 6736

You can create a custom namedtuple data type:

from collections import namedtuple

# create a new data type (internally it defines a class ContactData):
ContactData = namedtuple("ContactData", ["name", "city", "state"])

# create an object as instance of our new data type
alex = ContactData("Alex", "Taiwan", "Vietnam")

# access our new object
print(alex)             # output: ContactData(name='Alex', city='Taiwan', state='Vietnam')
print(alex.city)        # output: Taiwan
print(alex[1])          # output: Taiwan
alex[0] = "Alexander"   # set new value
print(alex.name)        # output: Alexander

Upvotes: 1

dokelung
dokelung

Reputation: 216

name tuple in module collections is also helpful:

>>> import collections
>>> Data = collections.namedtuple("Data", "name address home")
>>> Data('Alex', 'Taiwan', 'Vietnam')
>>> d = Data('Alex', 'Taiwan', 'Vietnam')
>>> d.name
'Alex'
>>> d.address
'Taiwan'
>>> d.home
'Vietnam'

Upvotes: 3

letmutx
letmutx

Reputation: 1416

You can use unpacking.

name, city, country = ["Alex","Taiwan","Vietnam"]
print name

In Python3, you can do much more using the * operator.

a, *b, c = [1, 2, 3, 4, 5] # a = 1, b = [2, 3, 4], c = 5

Refer PEP 448 -- Additional Unpacking Generalizations for more generalizations.

Upvotes: 6

Related Questions