0

Given input:

list = [['a']['a', 'c']['d']]

Expected Ouput:

mylist = a,c,d

Tried various possible ways, but the error recieved is TypeError: list indices must be integers not tuple.

Tried: 1.

k= []
list = [['a']['a', 'c']['d']]

#k=str(list)
for item in list:
       k+=item

print k

2.

print zip(*list)

etc.

Also to strip the opening and closing parenthesis.

Roman Bodnarchuk
  • 29,461
  • 12
  • 59
  • 75
Sirius
  • 736
  • 2
  • 9
  • 22
  • -1 Your post is very hard to read. Please indent your example code so it is nicely formatted. Also, reword your closing question so we know what you want to do with the opening and closing parenthesis (which I don't see anywhere). – MikeWyatt Aug 10 '11 at 18:41

2 Answers2

4

What you want is flattening a list.

>>> import itertools
>>> l
[['a'], ['a', 'c'], ['d']]
>>> res = list(itertools.chain.from_iterable(l))
>>> res
['a', 'a', 'c', 'd']
>>> set(res) #for uniqify, but doesn't preserve order
{'a', 'c', 'd'}

Edit: And your problem is, when defining a list, you should seperate values with a comma. So, not:

list = [['a']['a', 'c']['d']]

Use commas:

list = [['a'], ['a', 'c'], ['d']]

And also, using list as a variable is a bad idea, it conflicts with builtin list type.

And, if you want to use a for loop:

l = [['a'], ['a', 'c'], ['d']]
k = []

for sublist in l:
    for item in sublist:
        if item not in k: #if you want list to be unique.
            k.append(item)

But using itertools.chain is better idea and more pythonic I think.

Community
  • 1
  • 1
utdemir
  • 26,532
  • 10
  • 62
  • 81
  • @Utdemir: While implementing the above code using itertools.chain the keyword set also does get printed i.e. set['a', 'c', 'd']. Can you please tell me how do we get rid of that, sorry i am new to python. – Sirius Aug 10 '11 at 21:20
  • @Sam, If you don't use print statement or function anywhere, it never prints something. But if you use interactive console, it shows results string representation, it won't happen running from a file. – utdemir Aug 10 '11 at 22:44
0

While utdemir's answer does the job efficiently, I think you should read this - start from "11.6. Recursion". The first examples deals with a similar problem, so you'll see how to deal with these kinds of problems using the basic tools.

Dominik
  • 377
  • 4
  • 11