Ewro
Ewro

Reputation: 43

Append method making invalid list

I have an application where i read content from a json file, do some formatting and pass the list for another class.

When i print the first item i see this:

['.docx', '.ppt']

And the second is

['.py', '.java', '.cpp']

I append them to a list, but when i print the list this is the result:

[['.docx', '.ppt'], "['.py', '.java', '.cpp']"]

As this is an invalid list, i cant use for my methods who require a list as parameter.

Upvotes: 0

Views: 307

Answers (2)

Omer Tekbiyik
Omer Tekbiyik

Reputation: 4744

One of the solution is using extract like :

aList = ['.docx', '.ppt']
blist =['.py', '.java', '.cpp']

aList.extend(blist)
print (aList)

Second one is just using + means :

aList = ['.docx', '.ppt']
blist =['.py', '.java', '.cpp']

aList= aList + blist
print (aList)

Both output :

['.docx', '.ppt', '.py', '.java', '.cpp']

Using extract is more professional

Upvotes: 0

Mark
Mark

Reputation: 92440

Use extend(). append() adds the list (as a single reference) to the first list. extend() will add its contents:

a = ['.docx', '.ppt']
b = ['.py', '.java', '.cpp']
a.extend(b)
a
# ['.docx', '.ppt', '.py', '.java', '.cpp']

Upvotes: 2

Related Questions