Appending to 2 lists simultaneously - python

I have a piece of Python code that looks something like this:
array1 = []
array2 = []
def my_function():
# do some stuff
return x, y # both are integers
# append x to array1; append y to array2
What I'm trying to do is append the outputs of my_function to separate arrays. I understand that I need to somehow separate my_function's 2 outputs and then make 2 separate append() statements, but I'm not quite sure how to implement that.
Thanks in advance!

x, y = my_function() #get x,y returned from my_function()
# append x to array1; append y to array2
array1.append(x)
array2.append(y)

Related

List comprehensions in Python "freezing" Jupyter notebook

When I run the code below in Jupyter notebook, my "kernel" freezes (I get an asterisk between the square brackets like so: [*]):
x = [1,2,3,4]
for num in x:
x.append(num**2)
Why doesn't this code "append" the exponentiated numbers to the end of x?
The code below works and I understand why, but why doesn't the code above work:
x = [1,2,3,4]
out = []
for num in x:
out.append(num**2)
print(out)
You are iterating over a list, and in every iteration you append a new element to the list, so the iteration is never going to end.
To see what's happening, change your code to this:
import time
x = [1,2,3,4]
for num in x:
x.append(num**2)
time.sleep(0.5)
print(x)
If you know what you are doing, you can avoid this kind of "dynamic iteration" with the [:] trick:
x = [1,2,3,4]
for num in x[:]:
x.append(num**2)
This way you are iterating over x[:], not the growing x, in effect it's like you are iterating over a snapshot of x.
More concisely, you could use a list comprehension as follows:
x = [1,2,3,4]
x_squared = [elem**2 for elem in x]
x.extend(x_squared)

Get Delayed output of a variable

hey I have a Loop That is always running That keeps changing a variable Called X like this
And It keeps running And keeps changing. And I want to get the previous output of the variable. How Can I do this?
while True:
X = X+10
X = X*5
print(X)
You can put them in an array and select the last element of the array
I assume this is what you're looking for when you say previous output of variable. I'd suggest you to also read on loops if you've just started with python. Here's a source
while True:
print(x) #this will print value X after each iteration
x= x+10
x= x*5
The psuedo code:
arr1 = []
infinte loop:
x= x+10
x= x*5
append x to array
print arr1 index current time looping minus one

Numpy atleast_1d, but for lists

I have a function that takes as an argument either a list of objects or a single object. I then want to loop through the elements of the list or operate on the single object if it is not a list.
Below, I use numpy.atleast_1d().tolist() to ensure that a loop works whether or not the argument is a list or a single object. However, I am not sure if converting the object to a numpy array and then to a list may cause any unintended changes to the object.
Is there a way to ensure the argument is transformed into a list if it is not a list? I have two possible solutions in a simple example below, but wanted to know if there are any better ones.
import numpy as np
def printer1(x):
for xi in np.atleast_1d(x).tolist():
print(xi)
def printer2(x):
if type(x) != list:
x = [x]
for xi in x:
print(xi)
x1 = 'a'
x2 = ['a','b','c']
printer1(x1)
printer1(x2)
printer2(x1)
printer2(x2)
I'm using Python 2.7
In your function you can add check for array. I think this is one way to do it. You dont even need to use numpy for this.
def foo(x):
x = [x] if not isinstance(x, list) else x
printx # or do whatever you want to do
# or
for value in x:
print value
foo('a')
foo(['a','b'])
output:
['a']
a
['a', 'b']
a
b
To ensure that the element will be a list even that it has only one element, declare its value inside square brackets:
foo = ['stringexample']
foo2 = ['a','b']
for foos in foo:
print (foos)
for foos2 in foo2:
print (foos2)
This way, even that 'foo' has only a single string, it will still operate as a list with only one element.
Also, you could try this:
declare a empty list
use youremptylist.extend(incoming value)
It will iterate a new list for each incoming value, even that it is a single one
As Roni is saying, you can use this:
def printer(x):
finalList = []
finalList.extend(x)
print finalList
if x is a single value, it will be added to the finalList, if x is a list, it will be joined to finalList and you can iterate throught it.
If you want loopable things mostly untouched and non loopables behave like a 1-element list you could do something like:
def forceiter(x):
return getattr(x,"__iter__",lambda:(x,))()
Demo:
for x in [1,[2],range(3),"abc",(),{3:3,4:"x"}, np.logspace(0,3,4)]:
print(x,end=" --> ")
for i in forceiter(x):
print(i,end=" ")
print()
# 1 --> 1
# [2] --> 2
# range(0, 3) --> 0 1 2
# abc --> a b c
# () -->
# {3: 3, 4: 'x'} --> 3 4
# [ 1. 10. 100. 1000.] --> 1.0 10.0 100.0 1000.0

how to zip function with two arrays as a return value - Python

how do I create tuple from two randomly generated lists with separate function ? zip function will create only tuple of those two arrays as whole but I need the numbers to be coupled like (1,2),(3,4). Thanks.
import random
def ars():
arr1 = []
arr2 = []
for i in range(10):
x = random.randrange(100)
arr1.append(x)
for j in range(10):
y = random.randrange(100)
arr2.append(y)
return(arr1,arr2)
x = ars()
print x
y = zip(ars())
print y
zip function accepts multiple iterables as its arguments, so you simply have to unpack the values from the returned tuple with * (splat operator):
y = zip(*ars())
With zip(([1], [2])) only one iterable is submitted (that tuple).
In zip(*([1], [2])) you unpack 2 lists from tuple, so zip receives 2 iterables.
You can avoid having to zip by using map
def ars(arr_len, rand_max):
return [map(random.randrange, [rand_max]*2) for x in range(arr_len)]
call ars like: ars(10,100), if you really need tuples instead of lists, wrap the map statement in a tuple() function.

Python Lists.What am I missing?

from random import *
def f(one):
x=randrange(0,len(one))
y=randrange(0,len(one))
return(one)
print(one(["20","40","60"]))
the function is supposed to take an input parameter a list of strings and generates two random numbers between 0 and the length of the list but how do you return the list with the slice between the two numbers removed.
First you are not calling the function you've created, you must:
print( f(["20","40","60"]) )
Second, your function f() is not doing anything, is just creating two variables x and y but returning the same list it received as parameter.
And to return the sliced list:
from random import *
def f(one):
x=randrange(0,len(one))
y=randrange(0,len(one))
print (x, y)
return one[x:y]
print(f(["20","40","60"]))
Remember that randrange(x, y) returns a value between x and y - 1
The sublist of a list one from index i up to (but not including!) index j is written in Python as one[i:j]. I think you can figure out the rest from here.

Categories

Resources