1

Suppose I have these variables:

a = ['a','b','c']
b = 'yay'
c = 'cool'

I want to build a list d which contains:

['yay', 'a', 'b', 'c', 'cool']

I'd tried d = [b, a, c] but the result isn't what I wanted, it became:

['yay', ['a', 'b', 'c'], 'cool']

please if someone could help me.

4 Answers 4

7

You could do:

d = [b, *a, c]

To unpack the values of the list into the new list

Sign up to request clarification or add additional context in comments.

Comments

1

They way you are trying to add elements is adding a separate list try to use extend method of list which extends the previous list from the provided one

myList = []
myList.append(b)
myList.extend(a) #this is what you are looking for . 
myList.append(c)
print(myList) # ['yay', 'a', 'b', 'c', 'cool']

Comments

1

Just make the lists out of them and use addition operator + among the lists.

[b] + a + [c]

OUTPUT:

['yay', 'a', 'b', 'c', 'cool']

Comments

1

The .extend method will extend the list.

a = ['a','b','c']
b = 'yay'
c = 'cool'
d=[]
d.extend(a)
d.append(b)
d.append(c)

You can also do

a+[b]+[c]

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.