# [Tutor] Soem list operation questions?

Orri Ganel singingxduck at gmail.com
Tue Dec 28 05:24:38 CET 2004

```Hello kilovh.

> 1. Is there any easy way to compeltely reverse a list so that the last index
> becomes the first, etc.?

Why, yes. It's the 'reverse' method of lists. ie:

>>> li = [1,2,3,4]
>>> li.reverse()
>>> li
[4, 3, 2, 1]
>>>

> 2. Is there any way to take seperate integers in a list and combine them
> into digits of one number? (e.g. changing [1,2,3,4] into 1234)

It depends on what you're trying to do. If you want a string, then you
have to do the following:

>>> lista = [1,2,3,4]
>>> lin = ''.join([str(i) for i in li])
>>> lin
'1234'

Similarly, to make an int, just int() it:

>>> lista = [1,2,3,4]
>>> lin = int(''.join([str(i) for i in lista]))
>>> lin
1234

Now, let's look at the line that does all the work.

lin = ''.join([str(i) for i in li])

First things first. The expression: str.join(sequence) is a builtin of
strings which puts together all the elements of a sequence (assuming
the elements are strings), separated by str. In other words,
''.join(["a","b","c"]) returns "abc" (str in this case is an empty
string).

Now, even though lista is already a sequence, it is a sequence of
integers, so join won't work on it as is.  Which is why we use the
list comprehension. [str(i) for i in lista] does a number of things.
First, it makes a list (because it is between brackets), which is a
sequence, for join to work on. Secondly, it fixes the problem with
lista: it makes a sequence of strings, not integers ( [str(i) for i in
lista]   makes a new list with the elements of lista, but stringified
(that would be the technical term :-) )).

HTH,
Orri

> Thank you for your time.
>
> ~kilovh
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>

--
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.
```