Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining elements in a list without the join command

Tags:

python

join

list

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?

like image 789
Twhite1195 Avatar asked Apr 21 '15 02:04

Twhite1195


People also ask

How do you join all elements in a list?

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.

How do you join a certain element in a list Python?

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]]) .

How do you join a list element into a string?

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.

Can we join list in Python?

There are several ways to join, or concatenate, two or more lists in Python. One of the easiest ways are by using the + operator.


1 Answers

If you just want to print the number rather than return an actual int:

>>> a = [12,4,15,11]
>>> print(*a, sep='')
1241511
like image 172
TigerhawkT3 Avatar answered Oct 29 '22 01:10

TigerhawkT3