Sirius
Sirius

Reputation: 736

Combining elements in list using python

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.

Upvotes: 0

Views: 494

Answers (2)

utdemir
utdemir

Reputation: 27256

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.

Upvotes: 4

Dominik
Dominik

Reputation: 377

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.

Upvotes: 0

Related Questions