user3521180
user3521180

Reputation: 1130

how to get just the value of a list in another list?

Suppose I have a two lists:

a = [1,2,3,4,5]
b = [float]

My requirement is to just get the value of the 'a' list in 'b', i.e.

b = [1,2,3,4,5, float]

So, if we either append of insert, that will again create list of list, which I don't want.

Any suggestions

Upvotes: 2

Views: 290

Answers (3)

hiro protagonist
hiro protagonist

Reputation: 46859

this may be a bit clumsy, but it does what you want:

a = [1, 2, 3, 4, 5]
b = ["float"]

print(id(b))

for n in reversed(a):
    b.insert(0, n)
    
print(b)  # [1, 2, 3, 4, 5, 'float']
print(id(b))

note that the id does not change - no new list is created.

slice-assignment would also work:

b0 = b[0]
b[:len(a)] = a
b.append(b0)

if you don't mind working with a deque instead of a list you could also do this:

from collections import deque

a = [1, 2, 3, 4, 5]
b = deque(["float"])

b.extendleft(reversed(a))   # deque([1, 2, 3, 4, 5, 'float'])

Upvotes: 2

Joe Ferndz
Joe Ferndz

Reputation: 8508

Assume your input is:

a = [1,2,3,4,5]
b = ['float']

b{:] = a+b

print (b)

The output of this will be:

[1, 2, 3, 4, 5, 'float']

If your input is:

a = [1,2,3,4,5]
b = [float]

then your output will be:

[1, 2, 3, 4, 5, <class 'float'>]

Upvotes: 3

Zhubei Federer
Zhubei Federer

Reputation: 1270

you can use:

a.__add__(b)

output:

[1, 2, 3, 4, 5, <class 'float'>]

Upvotes: 1

Related Questions