I need to join the elements in a list without using the join command, so if for example I have the list:
[12,4,15,11]
The output should be:
1241511
Here is my code so far:
def lists(list1):
answer = 0
h = len(list1)
while list1 != []:
answer = answer + list1[0] * 10 ** h
h = h - 1
list1.pop(0)
print(answer)
But, in the end, the answer ends up being 125610
which is clearly wrong.
I think the logic is OK, but I can't find the problem?
Using join() method to concatenate items in a list to a single string. The join() is an inbuilt string function in Python used to join elements of the sequence separated by a string separator. This function joins elements of a sequence and makes it a string.
To join specific list elements (e.g., with indices 0 , 2 , and 4 ) and return the joined string that's the concatenation of all those, use the expression ''. join([lst[i] for i in [0, 2, 4]]) .
To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.
There are several ways to join, or concatenate, two or more lists in Python. One of the easiest ways are by using the + operator.
If you just want to print the number rather than return
an actual int
:
>>> a = [12,4,15,11]
>>> print(*a, sep='')
1241511
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With