javanewbie javanewbie - 1 month ago 9
Python Question

Adding 3 strings to the same index in a list

In this wxPython tutorial, I stumbled across this way to format a list:

packages = [('jessica alba', 'pomona', '1981'), ('sigourney weaver', 'new york', '1949'),
('angelina jolie', 'los angeles', '1975'), ('natalie portman', 'jerusalem', '1981'),
('rachel weiss', 'london', '1971'), ('scarlett johansson', 'new york', '1984' )]


How do you add to this list in such a format?
E.g.:

packages.append[(item1, item2, item3)]


The list was used to add content to a wx.ListCtrl widget like so:

for i in packages:
index = self.list.InsertStringItem(sys.maxint, i[0])
self.list.SetStringItem(index, 1, i[1])
self.list.SetStringItem(index, 2, i[2])


Thanks in advance for the help.

Answer

Note: The simplest answer to this question is

output = [(item[0],item[1],item[2]) for item.split(",") in someBigList]

Where item is a comma separated string.

The long answer.

Python has ability to store anything(yes, anything!) inside its iterable data structures. You can store lists inside list, dictionaries inside list and vice-versa, an object or a tuple or a set.

Tuple data-structure is widely used in Python and the main difference between a tuple and a list is that, you cannot change contents inside a tuple, while you can do that in a list. Immutability is just one of the advantages of using tuples. There are many more advantages.

Let's say you have the data above coming in some form and you have to group these all. Lets say they were strings separated by a comma, as in a csv.

with open("/tmp/test.csv","r") as readFl:
    line = readFl.readlines()

lines
Out[5]: 
['jessica alba, pomona, 1981',
 'sigourney weaver, new york, 1949',
 'angelina jolie, los angeles, 1975',
 'natalie portman, jerusalem, 1981',
 'rachel weiss, london, 1971',
 'scarlett johansson, new york, 1984']

Now there is a requirement to access each element in each of the elements of the list lines. For this we use a list of tuples.

output = []
for line in lines:
    row = tuple(line.split(",")) # by default, split() returns a list, we cast it to a tuple.
    output.append(row)


output
Out[16]: 
[('jessica alba', 'pomona', '1981'),
 ('sigourney weaver', 'new york', '1949'),
 ('angelina jolie', 'los angeles', '1975'),
 ('natalie portman', 'jerusalem', '1981'),
 ('rachel weiss', 'london', '1971'),
 ('scarlett johansson', 'new york', '1984')]

Hope this helped.