2

For example i have the below list

list1 = [] 
list2 = ['cat', 'tiger']

I wanted to add only the individual elements in the list2 into list1. For eg,

list1.append(['wolf', list2])

And wanted the output like,

[[wolf, cat, tiger]]

But instead I get like,

[['wolf', ['cat', 'tiger']]]

I don't want list2 as such getting appended with the brackets, rather only the elements from the list2. Am i missing something ? Please add your comments. This is just an example from a bigger problem.

0

2 Answers 2

3

Use unpacking

>>> list1.append(['wolf', *list2])

[['wolf', 'cat', 'tiger']]

In case python2

>>> list1.append(['wolf'] + list2)
Sign up to request clarification or add additional context in comments.

4 Comments

It says File "txtwrp.py", line 52 list1.append(['wolf', *list2]) ^ SyntaxError: invalid syntax
@Desperado your older python version probably has no unpacking yet. Try edited
So then it's not a duplicate. It's tagged python 2.7
@ᴡʜᴀᴄᴋᴀᴍᴀᴅᴏᴏᴅʟᴇ3000 fair enough :)
1

Try this:

list1=[["wolf"]+list2]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.