Generate one list with multiple elements - python

I'm trying to generate a list of 100 triangular numbers. This is what I have for generating 100 triangular numbers. When I run it I get 100 lists, how can I change it to generate one list with 100 elements?
def Triangular():
n=0
while n<101:
n=1+n
triangleNumbers = (n*(n+1))//2
print ([triangleNumbers])
Triangular()
Desired Result: [1,3,6,..]
Actual Result:
[1]
[3]
[6]
[10]
[15]
[21]
[28]
...

You need to difine a list , and use the list metohds to help you, code below should solve your problem.
def Triangular():
n=0
result=[]
while n<101:
n=1+n
triangleNumbers = (n*(n+1))//2
result.append(triangleNumbers)
print result
Triangular()

print ([triangleNumbers])
Look at the above statement.
You are creating a new list rather then adding to a list.
>>print (type([triangleNumbers]))
<type 'list'>
Instead,
Initialize an empty list.
append triangleNumbers to the list at every iteration.
Sample code:
lst=[]
def Triangular():
n=0
while n<101:
n=1+n
triangleNumbers = (n*(n+1))//2
lst.append(triangleNumbers)
print lst
Triangular()

To make it more pythonic, you could use a list comprehension
def Triangular(upto):
lst = [(n*(n+1))//2 for n in range(1,upto)]
print lst
Personally I'd make the function return the list only, then let the caller print the result
def Triangular(upto):
return [(n*(n+1))//2 for n in range(1,upto)]
lst = Triangular(101)
print lst

You can do like this too :
lis =[]
for n in range(100):
lis.append((n*(n+1))//2)
print (lis)

Related

How to select specific elements in a list and use them (Python)

numbers = [1,2,3,4,5]
How can I pick one element and use it in a calculation?
For example, to pick just the second element on its own. Would it then be possible to store it in another list?
Thanks
You can access and item by its index.
list = ["A","B","C"]
list[0] // returns A
IIUC:
>>> l=[]
>>> numbers=[1,2,3,4,5]
>>> l.append(numbers[1])
>>> l
[2]
>>>
Use append and indexing.
And then, l will have a value which is the second element of numbers.
You can do something like this:
numbers=[1,2,3,4,5]
# Picking up '2' from the list
no = numbers[1] # Since list index starts at 0
print(no) # Prints 2
For storing in another list, you need to declare an empty list where you'll store the value. Like below:
l = []
l.append(no) # Now l contains 2
print(l) # Prints [2]

How to merge n lists together item by item for each list

I want to make one large list for entering into a database with values from 4 different lists. I want it to be like
[[list1[0], list2[0], list3[0], list4[0]], [list1[1], list2[1], list3[1], list4[1]], etc.....]
Another issue is that currently the data is received like this:
[ [ [list1[0], list1[1], [list1[3]]], [[list2[0]]], etc.....]
I've tried looping through each list using indexs and adding them to a new list based on those but it hasn't worked, I'm pretty sure it didn't work because some of the lists are different lengths (they're not meant to be but it's automated data so sometimes there's a mistake).
Anyone know what's the best way to go about this? Thanks.
First list can be constructed using zip function as follows (for 4 lists):
list1 = [1,2,3,4]
list2 = [5,6,7,8]
list3 = [9,10,11,12]
list4 = [13,14,15,16]
res = list(zip(list1,list2,list3,list4))
For arbitrtary number of lists stored in another list u can use *-notation to unpack outer list:
lists = [...]
res = list(zip(*lists))
To construct list of lists for zipping from you data in second issue use flatten concept to it and then zip:
def flatten(l):
res = []
for el in l:
if(isinstance(el, list)):
res += flatten(el)
else:
res.append(el)
return res
auto_data = [...]
res = list(zip(*[flatten(el) for el in auto_data]))
Some clarification at the end:
zip function construct results of the smallest length between all inputs, then you need to extend data in list comprehension in last code string to be one length to not lose some info.
So if I understand correctly, this is your input:
l = [[1.1,1.2,1.3,1.4],[2.1,2.2,2.3,2.4],[3.1,3.2,3.3,3.4],[4.1,4.2,4.3,4.4]]
and you would like to have this output
[[1.1,2.1,3.1,4.1],...]
If so, this could be done by using zip
zip(*l)
Make a for loop which only gives you the counter variable. Use that variable to index the lists. Make a temporary list , fill it up with the values from the other lists. Add that list to the final one. With this you will et the desired structure.
nestedlist = []
for counter in range(0,x):
temporarylist = []
temporarylist.append(firstlist[counter])
temporarylist.append(secondlist[counter])
temporarylist.append(thirdlist[counter])
temporarylist.append(fourthlist[counter])
nestedlist.append(temporarylist)
If all the 4 lists are the same length you can use this code to make it even nicer.
nestedlist = []
for counter in range(0,len(firstlist)): #changed line
temporarylist = []
temporarylist.append(firstlist[counter])
temporarylist.append(secondlist[counter])
temporarylist.append(thirdlist[counter])
temporarylist.append(fourthlist[counter])
nestedlist.append(temporarylist)
This comprehension should work, with a little help from zip:
mylist = [i for i in zip(list1, list2, list3, list4)]
But this assumes all the list are of the same length. If that's not the case (or you're not sure of that), you can "pad" them first, to be of same length.
def padlist(some_list, desired_length, pad_with):
while len(some_list) < desired_length:
some_list.append(pad_with)
return some_list
list_of_lists = [list1, list2, list3, list4]
maxlength = len(max(list_of_lists, key=len))
list_of_lists = [padlist(l, maxlength, 0) for l in list_of_lists]
And now do the above comprehension statement, works well in my testing of it
mylist = [i for i in zip(*list_of_lists)]
If the flatten concept doesn't work, try this out:
import numpy as np
myArray = np.array([[list1[0], list2[0], list3[0], list4[0]], [list1[1], list2[1], list3[1], list4[1]]])
np.hstack(myArray)
Also that one should work:
np.concatenate(myArray, axis=1)
Just for those who will search for the solution of this problem when lists are of the same length:
def flatten(lists):
results = []
for numbers in lists:
for output in numbers:
results.append(output)
return results
print(flatten(n))

python program shows errors in arranging element of list in sorted order

I wrote this program to join all the elements of sub-lists in a single result empty list and then sort the returned result list. But after i run this program i get a unusual output. I get None on console screen.
What's wrong here in this code?
n=[[44,45,76,8,678,24,24],[45,45737,45,7373]]
def makelist(lis):
result= []
for i in lis:
for j in i:
result.append(j)
return result
print makelist(n).sort()
n=[[44,45,76,8,678,24,24],[45,45737,45,7373]]
def makelist(lis):
result= []
for i in lis:
for j in i:
result.append(j)
return result
All this is OK. Now run:
y = makelist(n)
y.sort()
print y
Your list is sorted and stored in the 'y' variable.
makelist(n).sort() does not return anything
Do it like
temp = makelist(n)
temp.sort()
print temp
Given a list lst and then calling sort will sort the list in-place, but it wiil not return the sorted list.
An example solution:
# Make this work in Python2 and Python3
from __future__ import print_function
import itertools
n=[[44,45,76,8,678,24,24],[45,45737,45,7373]]
def makelist(lis):
result= []
for i in lis:
for j in i:
result.append(j)
return result
# Variation 1
print(sorted(makelist(n)))
# Variation 2
lst = makelist(n)
lst.sort()
print(lst)
# Variation 3 (replacing the makelist flattening operation)
lst = list(itertools.chain.from_iterable(n))
lst.sort()
print(lst)
Use sorted method instead of sort and this will fix your problem:
n=[[44,45,76,8,678,24,24],[45,45737,45,7373]]
def makelist(lis):
result= []
for i in lis:
for j in i:
result.append(j)
return result
print sorted(makelist(n))
# OR check this way
res = makelist(n)
print res
res.sort()
print res
To read more about sort() you can use the following link: http://www.tutorialspoint.com/python/list_sort.htm
sort() is a method of list. It sorts the list in place and does not return the list as a reminder of that fact.
sorted() is a builtin function, not a method on list, because it's
more general taking any iterator as its first argument, not just a list. It of course does return a list.
n=[[44,45,76,8,678,24,24],[45,45737,45,7373]]
def makelist(lis):
result= []
for i in lis:
for j in i:
result.append(j)
return result
print sorted(makelist(n))
The .sort() method of lists sorts the list in place, while sorted() creates a new list.
sort() function sorts in-place and returns None. On the other hand, sorted() function returns a new list. Thus, you can use your current implementation:
makelist(n).sort()
print(n)
Or, you can use sorted():
print sorted(makelist(n), key=int)

Create and add a new array

I have a while loop that pulls down values and prints them individually. How can I get these individually printed values into one array? Ideally I would put something in my while loop and continuously add to an array with my numeric values.
If you want to do this in a for loop:
valuesToBePulledDown = [1,2,3,4,5,6,7,8,9]
array=[i for i in valuesToBePulledDown]
print array
Use a list comprehension:
print [i for i in xrange(100)]
If you want to iterate over a specific list:
my_list = [4,3,2,1,5,3,2]
print [i for i in my_list]
Maybe you would like to do something to each value before adding it to the list:
my_list = [1,2,3,4,5]
print [i*i for i in my_list] # prints [1,4,9,16,25]
This should get you started.
However, if you are insistent on using a while loop:
count = 0
my_values = []
while count < 10:
my_values.append(count)
count += 1
print my_values # prints [0,1,2,3,4,5,6,7,8,9]
Although, if you want to use an explicit looping construct, this particular scenario lends itself to a for loop:
my_values = []
for i in xrange(10):
my_values.append(i)
print my_values # prints [0,1,2,3,4,5,6,7,8,9]
Needless to say, as with the list comprehensions, you can use any iteratable object, not just xrange() in for loop.
I think that you wanted to say "append" instead of "print", and "list" instead of "array".
valuesToBePulledDown = [1,2,3,4,5,6,7,8,9]
array = []
i = 0
while i<len(valuesToBePulledDown):
array.append(i)
print i
i += 1
By the way, I would recomend you to use a for loop instead a "while", but that's what you asked for.

How to cycle through items in an list and have each item get fed into a function [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Python: For each list element apply a function across the list
for example, let's say I have an array or list
myList = [a,b,c,d]
and I have a function that generates a random number.
How do I go through the list and have each of the
item in that list receives the random number generated by the
function and be added to the item?
So, say 'a' is the 1st in the list, 'a' goes into the function where a random number (let's say 5), is generated and adds itself to 'a' the result should be `[a+5, b+.......].
You use a list comprehension:
[func(elem) for elem in lst]
For your specific example, you can use an expression that sums the values:
[elem + func() for elem in myList]
where func() returns your random number.
Use map() function, that apply function to every item of iterable and return a list of the results:
def myfunc(x):
return x ** 2
>>> map(func, [1,2,3])
[1, 4, 9]
If you need one liner :-)
myList = [1,2,3,4]
[ i + map(lambda i: random.randint(10,20), myList)[index] for index, i in enumerate(myList) ]
I assume you're talking about integers. This little script should do what you want:
import random
def gen_rand(number):
generated = random.randint(1, 10) # you can specify whatever range you want
print generated
return number + generated
myList = [1,2,3,4,5]
print str(myList)
myList = [gen_rand(item) for item in myList]
print str(myList)
Or you could use the map function instead of the for loop.
Replace
myList = [gen_rand(item) for item in myList]
with
myList = map(gen_rand,myList)

Categories