dzdws
dzdws

Reputation: 89

Building List from Variables in Python

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.

Upvotes: 1

Views: 69

Answers (4)

user15801675
user15801675

Reputation:

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]

Upvotes: 1

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95872

You could do:

d = [b, *a, c]

To unpack the values of the list into the new list

Upvotes: 7

ThePyGuy
ThePyGuy

Reputation: 18406

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

[b] + a + [c]

OUTPUT:

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

Upvotes: 1

Zain Ul Abidin
Zain Ul Abidin

Reputation: 2690

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']

Upvotes: 1

Related Questions