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.

asked Jun 22, 2021 at 7:29

4 Answers 4

7

You could do:

d = [b, *a, c]

To unpack the values of the list into the new list

answered Jun 22, 2021 at 7:35
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']
answered Jun 22, 2021 at 7:33
1

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

[b] + a + [c]

OUTPUT:

['yay', 'a', 'b', 'c', 'cool']
answered Jun 22, 2021 at 7:34
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]
answered Jun 22, 2021 at 7:37

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.