Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python one-line "for" expression

Tags:

python

lambda

I'm not sure if I need a lambda, or something else. But still, I need the following:

I have an array = [1,2,3,4,5]. I need to put this array, for instance, into another array. But write it all in one line.

for item in array:
    array2.append(item)

I know that this is completely possible to iterate through the items and make it one-line. But googling and reading manuals didn't help me that much... if you can just give me a hint or name this thing so that I could find what that is, I would really appreciate it.

Update: let's say this: array2 = SOME FANCY EXPRESSION THAT IS GOING TO GET ALL THE DATA FROM THE FIRST ONE

(the example is NOT real. I'm just trying to iterate through different chunks of data, but that's the best I could come up with)

like image 973
0100110010101 Avatar asked Oct 09 '09 17:10

0100110010101


People also ask

How do you print only one line in Python?

To print on the same line in Python, add a second argument, end=' ', to the print() function call. print("It's me.")

What is single line in Python?

What is a single line comment in python? Single line comments are those comments which are written without giving a line break or newline in python. A python comment is written by initializing the text of comment with a # and terminates when the end of line is encountered.


5 Answers

The keyword you're looking for is list comprehensions:

>>> x = [1, 2, 3, 4, 5]
>>> y = [2*a for a in x if a % 2 == 1]
>>> print(y)
[2, 6, 10]
like image 170
Adam Rosenfield Avatar answered Oct 01 '22 12:10

Adam Rosenfield


for item in array: array2.append (item)

Or, in this case:

array2 += array
like image 40
liori Avatar answered Oct 01 '22 11:10

liori


If you really only need to add the items in one array to another, the '+' operator is already overloaded to do that, incidentally:

a1 = [1,2,3,4,5]
a2 = [6,7,8,9]
a1 + a2
--> [1, 2, 3, 4, 5, 6, 7, 8, 9]
like image 25
ewall Avatar answered Oct 01 '22 10:10

ewall


Even array2.extend(array1) will work.

like image 45
Prabhu Avatar answered Oct 01 '22 10:10

Prabhu


If you're trying to copy the array:

array2 = array[:]
like image 38
a paid nerd Avatar answered Oct 01 '22 11:10

a paid nerd