Newbie Q: Adding String to list
Hans.Aschauer at Physik.uni-muenchen.de
Thu Aug 1 10:37:41 CEST 2002
> Newbie questions - I'm trying to improve my skills by trying to code more
> efficiently, and all help will be appreciated.
> I have an array
> AA = ["a","b","c"]
> I'd like to add text, let's say
> x = "x"
> to each element of the array, to get
> AAx = ["xa","xb","xc"]
AAx = [ 'x' + i for i in AA]
> What's the simplest way to accomplish this?
> I'd like to avoid looping over AA.
This is called 'list comprehension'. Have a look at the tutorial, it is
explained there. Please note that a recent python (python >= 2.1(?)) is
> And if
> X = ["x","y","z"]
> what's the best way to generate (the equivalent of)
> AAXX = |"xa","xb","xc"|
> AAX = ["xa","xb","xc","ya","yb","yc","za","zb","zc"]
AAX = [i+j for i in X for j in AA]
> if I have an array with N elements, what's the best way to convert this
> into a 2 dimensional array with (n X m) elements, where n*m = N. And vice
n = 3
m = 2
a = [1,2,3,4,5,6]
M = [ a[n*i:n*(i+1)] for i in range(m)]
and back again:
aa = [i for b in M for i in b]
> I need to be able to do this with numeric data too, but I should be able
> to figure that out from any hints I receive from above.
For heavy numeric stuff I would recommend using the "Numerical Python"
library or similar (however, for my numeric stuff standart python is
More information about the Python-list