How to append data inside the first list into the second list and eliminate newline for data in y. For example, y = ['2\n'] x = ['22 34 55 \n']
expected output : output = [' 2 22 34 55 \n']
I have tried .join syntax but i didnt get the output as I expected.
CodePudding user response:
If you are trying to merge two lists into one you can use Mechanic pig's method:
y = ["2"]
x = ["22", "34", "55"]
z = y x
# y and x will remain ["2"] and ["22", "34", "55"]
# z will be ["2", "22", "34", "55"]
If you are trying to append values to a list you can use the list.extend method:
y = ["2"]
x = ["22", "34", "55"]
y.extend(x)
# x will remain ["22", "34", "55"]
# y will become ["2", "22", "34", "55"]
Or if you want to prepend a list to a list insert the elements of list y from back to front into x:
y = ["2"]
x = ["22", "34", "55"]
for element in y[::-1]:
x.insert(0, element)
# x will become ["2", "22", "34", "55"]
# y will remain ["2"]
CodePudding user response:
We can use the extend()
method and combine both the lists.
We can also use a lambda function to iterate the list x, and append the item as shown.
I have attached the code below.
y=[2]
x=[22, 34, 55]
y.extend(x)
print(y) # prints [2, 22, 34, 55]
y=[2]
y.extend([i for i in x])
print(y) # prints [2, 22, 34, 55]