Using for loops to create multiple lists - python

Currently I have a function.
def create1(n):
output = []
for i in range(n):
output.append(int(i)+1)
return output
It returns [1,2,3] whenever enter create(3). However, I want it to return [[1],[1,2],[1,2,3]].
I know there's a problem with something in my for loop but I can't figure it out.

Use range() to create lists of numbers quickly:
def create1(n):
output = []
for i in range(n):
output.append(range(1, i + 2))
return output
or, using a list comprehension:
def create1(n):
return [range(1, i + 2) for i in range(n)]
If you are using Python 3, turn the iterator returned by range() into a list first:
for i in range(n):
output.append(list(range(1, i + 2)))
Quick demo:
>>> def create1(n):
... return [range(1, i + 2) for i in range(n)]
...
>>> create1(3)
[[1], [1, 2], [1, 2, 3]]

This works in Python 2 and Python 3:
>>> def create1(n):
... return [list(range(1,i+1)) for i in range(1,n+1)]
...
>>> create1(5)
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]

Try this:
def create(n):
output = []
for i in range(n):
output.append(range(1,i+2))
return output
print create(3)

What you really want is a list appended at every stage. So try this
def create1(n):
output = []
for i in range(n):
output.append(range(1,i+2)) # append a list, not a number.
return output
range(n) gives you a list of integers from 0 to n-1. So, at each stage (at each i), you're appending to the output a list from 0 to i+1.

Related

How to iterate the first index value twice before going to the next index position?

I'm trying to make a for loop that iterates each index twice before going to the next one, for example if I have the following list:
l = [1,2,3]
I would like to iterate it if it was in this way:
l = [1,1,2,2,3,3]
could someone help me with this problem please?
The most obvious thing would be a generator function that yields each item in the iterable twice:
def twice(arr):
for val in arr:
yield val
yield val
for x in twice([1, 2, 3]):
print(x)
If you need a list, then
l = list(twice([1, 2, 3]))
You could make a list comprehension that repeats the elements and flattens the result:
l = [1,2,3]
repeat = 2
[n for i in l for n in [i]*repeat]
# [1, 1, 2, 2, 3, 3]
You can solve this by using NumPy.
import numpy as np
l = np.repeat([1,2,3],2)
Repeat repeats elements of an array the specified number of times. This also returns a NumPy array. This can be converted back to a list if you wish with list(l). However, NumPy arrays act similar to lists so most of the time you don't need to change anything.
Unsurprisingly, more-itertools has that:
>>> from more_itertools import repeat_each
>>> for x in repeat_each([1, 2, 3]):
... print(x)
...
1
1
2
2
3
3
(It also has an optional second parameter for telling it how often to repeat each. For example repeat_each([1, 2, 3], 5). Default is 2.)
l = [1, 2, 3]
lst = []
for x in l:
for i in range(2):
lst.append(x)
print(lst)
# [1, 1, 2, 2, 3, 3]

How do I reverse a list using while loop?

Input list: [1, 2, 3, 4, 5]
Output: [5, 4, 3, 2, 1]
I know how to do it with for loop, but my assignment is to do it with while loop; which I have no idea to do. Here is the code I have so far:
def while_version(items):
a = 0
b = len(items)
r_list = []
while (a!=b):
items[a:a] = r_list[(-a)-1]
a+=1
return items
I would say to make the while loop act like a for loop.
firstList = [1,2,3]
secondList=[]
counter = len(firstList)-1
while counter >= 0:
secondList.append(firstList[counter])
counter -= 1
The simplest way would be:
def while_version(items):
new_list = []
while items: # i.e. until it's an empty list
new_list.append(items.pop(-1))
return new_list
This will reverse the list:
>>> l1 = [1, 2, 3]
>>> l2 = while_version(l)
>>> l2
[3, 2, 1]
Note, however, that it also empties the original list:
>>> l1
[]
To avoid this, call e.g. l2 = while_version(l1[:]).
The trivial answer
Given
a = [1, 2, 3, 4, 5]
then
a[::-1]
returns
[5, 4, 3, 2, 1]
In your code:
You use r_list[(-a)+1], buy you have never assigned r_list any value (just "r_list = []")
I think your are confusing "items" with "r_list". So I think you want to return "r_list" instead of "items" (the input parameter)
The assignment should be "r_list[a] = items[-a-1]", but that doesn't work. You should use "r_list.append(items[-a-1])"
The return should be "return r_list"
"while (a!=b)" should be "while (a < b)" for readeability
Hope this helps

Creating a recursive function that gets the sum of all possible subsets in a list of integers

If i were to get the sum of all possible subset-combinations in the list [1,2,3] i would use the code below:
def f():
for i in range(2):
for j in range(2):
for k in range(2):
x = i*1 + j*2 + k*3
print x
f()
How can i make a recursive function that does this for any list?
I can solve this using itertools.combinations but i would like to learn the recursive way.
Thanks
Let's write a recursive function to output all combinations of all subsets of a list.
For a given list, the combinations are the the list itself, plus all combinations of the list minus each member. That's easy to translate straight to Python:
def combinations(seq):
yield seq
for i in range(len(seq)):
for combination in combinations(seq[:i] + seq[i+1:]):
yield combination
However, this will obviously yield duplicates. For example, the list [1, 2, 3] contains both [1, 2] and [1, 3], and they both contain [1]. So, how do you eliminate those duplicates? Simple, just tell each sub-list how many elements to skip:
def combinations(seq, toskip=0):
yield seq
for i in range(toskip, len(seq)):
for combination in combinations(seq[:i] + seq[i+1:], i):
yield combination
Now, you want to sum all combinations? That's easy:
>>> a = [1, 2, 3]
>>> map(sum, combinations(a))
[6, 5, 3, 0, 2, 4, 1, 3]
def allsums(a):
x = a[0]
if len(a) > 1:
yy = allsums(a[1:])
return set(x + y for y in yy).union(yy)
else:
return set([0, x])

Getting lists where an element passes through every index in python?

Kind of a strange request.
Let's say I have the following list:
[1,2,3]
And I want something, say, the number 9, to pass through every index, to get the following list of lists:
[[9,1,2,3],
[1,9,2,3],
[1,2,9,3],
[1,2,3,9]]
Any idea how to do this easily? Also, is there a name for this sort of thing?
Edit: I realize I can do something like the following:
lists=[]
for i in range(4):
new_list = [1,2,3]
new_list.insert(i,9)
lists+=[new_list]
but I consider this inelegant. Thoughts?
You could do something like
l = [1,2,3]
new_l = [l[:i] + [9] + l[i:] for i in range(len(l) + 1)]
How about a for loop:
l = [1,2,3]
res = []
for i in xrange(len(l)+1):
l2 = l[:]
l2.insert(i,9)
res.append(l2)
Here is another thing I thought of:
l = [1,2,3]
q = [l[:] for _ in range(len(l)+1)]
map(lambda(x):x.insert(q.index(x),9), q)
Then q will contain your list:
print q
[9, 1, 2, 3], [1, 9, 2, 3], [1, 2, 9, 3], [1, 2, 3, 9]]
enumerate and repeat are your friends.
from itertools import repeat
some_list = [1, 2, 3]
new_lists = []
new_elt = 9
for i, lst in enumerate(L[:] for L in repeat(some_list, len(some_list)+1))
lst.insert(i, new_elt)
new_lists.append(lst)
print new_lists

return a list containing elements of another list

I need to write an expression and I'm completely stuck. I have part of the code that I think I have written correctly but I'm stick on the rest of it. I need the code to return a new list containing every 3rd element in the list, starting at index 0.
For example: if I have the list [0, 1, 2, 3, 4, 5] I need it to return [0, 3]
The code I have so far is:
result = []
i = 0
while i < len(L):
result.append(L[i])
i =
return result
Can someone please help me figure out what I need the i = expression to be for this code to work.
First of all, you can make use of extended slice notation to make things easier:
In [1]: l = [0, 1, 2, 3, 4, 5]
In [2]: l[::3]
Out[2]: [0, 3]
From the docs:
Some sequences also support “extended slicing” with a third “step” parameter: a[i:j:k] selects all items of a with index x where x = i + n*k, n >= 0 and i <= x < j.
As for your code sample, you probably need i = i + 3 or i += 3 there.
Maybe try this:
result = []
for i in range(0, len(L), 3):
result.append(L[i])
return result
Another alternative is to use enumerate.
[j for i, j in enumerate([0, 1, 2, 3, 4, 5]) if i % 3 == 0]
this will give tyou an iterable sequence:
import itertools
l = [0, 1, 2, 3, 4, 5]
itertools.islice(l, 0, None, 3)
to turn it into a list, use the list() function.
impiort itertools
def get_sublist(l):
return list(itertools.islice(l, 0, None, 3))
python 3.2
one way:
>>> [i for i in range(0,len(L),3)]
[0,3]
your method:
result = []
i = 0
while i <= len(L):
result.append(L[i])
i+=3
return result

Categories