I am trying to put a series of multiplications inside a list, I am using the code below:
listx = []
for i in range (2):
list = [(3*i)]
listx.append(list)
The problem is that this will put the two results inside two separate lists inside a lists, I just wants the floats to be inside the first list.
listx = []
for i in range (2):
listx.append(3*i)
Just use this one. There is no need to create another list for storing the result. You created another list to store the value and appended that list into your listx
You can also use list comprehensions. Basically it's the same with for cycles but it's much shorter and for simpler operations like yours it's easier to read.
listx = [i*3 for i in range(2)]
This should produce a single list with values multiplied by 3 as integers
Related
I am looking for a solution to change the last two lists in a list of lists. The number of lists inside the list is variable. The change of the values depends on every time the last two lists.
list_of_colors=[['red','red','red','red'],['red','red','red','red'],
['red','red','red','red'], ['red','red','red','red']]
I expect the second to the last list changes completely from 'red' to 'lightgrey' and in the last list, only the last two from 'red' into 'lightgrey' - like this:
list_of_colors=[['red','red','red','red'],['red','red','red','red'],
['lightgrey','lightgrey','lightgrey','lightgrey'], ['red','red','lightgrey','lightgrey']]
This list of lists is to color a plotly table - Thanks for the help
For a more dynamic solution, i.e. in case the lists don't have a fixed length, you can try this:
list_of_colors[-2] = ['lightgrey'] * len(list_of_colors[-2])
last_n = 2
list_of_colors[-1][-last_n:] = ['lightgrey'] * last_n
In the last_n variable, I have specified the number of elements you wish to change, of the last list.
If I understood your question correctly, the parent list which contains the lists can have variable number of lists inside it, and you specifically know what values you require inside the last two lists, Then, this should work:
list_of_colors[-1] = ['lightgrey','lightgrey','lightgrey','lightgrey']
list_of_colors[-2] = ['red','red','lightgrey','lightgrey']
I have a list of lists in my script:
list = [[1,2]
[4,3]
[6,2]
[1,6]
[9,2]
[6,5]]
I am looking for a solution to sum up the contents of each "sublist" within the list of lists. The desired output would be:
new_list = [3,7,8,7,11,11]
I know about combining ALL of these lists into one which would be:
new_list = [27,20]
But that's not what i'm looking to accomplish.
I need to combine the two values within these "sublists" and have them remain as their own entry in the main list.
I would also greatly appreciate it if it was also explained how you solved the problem rather than just handing me the solution. I'm trying to learn python so even a minor explanation would be greatly appreciated.
Using Python 3.7.4
Thanks, Riftie.
The "manual" solution will be using a for loop.
new_list = []
for sub_list in list:
new_list.append(sum(sub_list))
or as list compherension:
new_list = [sum(sub_list) for sub_list in list]
The for loop iterates through the elements of list. In your case, list is a list of lists. So every element is a list byitself. That means that while iterating, sub_list is a simple list. To get a sum of list I used sum() build-in function. You can of course iterate manually and sum every element:
new_list = []
for sub_list in list:
sum_val = 0
for element in sub_list:
sum_val = sum_val + element
new_list.append(sum_val)
but no need for that.
A better approach will be to use numpy, which allows you to sum by axis, as it looks on list of lists like an array. Since you are learning basic python, it's too soon to learn about numpy. Just keep in mind that there is a package for handling multi-dimensions arrays and it allows it perform some actions like sum on an axis by your choice.
Edit: I've seen the other solution suggest. As both will work, I believe this solution is more "accessible" for someone who learn to program for first time. Using list comprehension is great and correct, but may be a bit confusing while first learning. Also as suggested, calling your variables list is a bad idea because it's keyword. Better names will be "my_list", "tmp_list" or something else.
Use list comprehension. Also avoid using keywords as variable names, in your case you overrode the builtin list.
# a, b -> sequence unpacking
summed = [a + b for a, b in lst] # where lst is your list of lists
# if the inner lists contain variable number of elements, a more
# concise solution would be
summed2 = [sum(seq) for seq in lst]
Read more about the powerful list comprehension here.
I have two lists (list_1,list_2) and a function which returns two lists (list_1_f, list_2_f) and I would like to add the items of list_1_f to list_1 and the items of list_2_f to list_2:
def lists():
list_1_f = [10,10,10]
list_2_f = [20,20,20]
return list_1_f,list_2_f
list_1, list_2 = [1,1,1], [2,2,2]
The case is that I always have 2 original lists and the extension is going to be done just for another two extra lists. So that at the end I would have two lists with the original items plus the ones got from the function, and the output would be:
list_1 = [1,1,1,10,10,10]
list_2 = [2,2,2,20,20,20]
I have tried the following lines using extend function but none works:
list_1.extend([]), list_2.extend([]) = lists()
list_1.extend(), list_2.extend() = lists()
list_1.extend, list_2.extend = lists()
I could always do the following:
list_1a, list_2a = lists()
list_1.extend(list_1a)
list_2.extend(list_2a)
But I was wondering if it is even possible to make the extension without having to create two intermediate lists.
It is not directly possible, because what must be on the left side of an assignment cannot be a function call. It can only be built from simple variables, data members, subscripts and commas, parentheses or square brackets.
Best that can be done is to use a comprehension or a map on the right side:
list_1, list_2 = map(lambda x: sum(x, []), zip((list_1, list_2), lists()))
(thanks to #meowgoesthedog for that way)
Whether it is better that a clear code using 3 lines is up to the reader. IMHO the only real use case would be inside a lambda which only supports a unique expression
I am initializing my list object using following code.
list = [
func1(centroids[0],value),
func1(centroids[1],value),
....,
func1(centroids[n],value)]
I am trying to do it a more elegant way using some inline iteration. Following is the pseudo code of one possible way.
list = [value for value in func1(centroids[n],value)]
I am not clear how to call func1 in an iterative way. Can you suggest a possible implementation?
For a list of objects, Python knows how to iterate over it directly so you can eliminate the index shown in most of the other answers,
res = [func1(c, value) for c in centroids]
That's all there is to it.
A simple list comprehension consists of the "template" list element, followed by the iterator needed to step through the desired values.
my_list = [func1(centroids[0],value)
for n in range(n+1)]
Use this code:
list = [func1(centroids[x], value) for x in range(n)]
This is called a list comprehension. Put the values that you want the list to contain up front, then followed by the for loop. You can use the iterating variable of the for loop with the value. In this code, you set up n number(s) of variable(s) from the function call func1(centroids[x], value). If the variable n equals to, let's say, 4, list = [func1(centroids[0], value), func1(centroids[0], value), func1(centroids[0], value), func1(centroids[0], value)] would be equal to the code above
I am creating a list in python in the following way:
new_points = [None] * 25
for point in points:
new_points[point.id] = point
I am wondering if this can be achieved by Python one-line list comprehension. Please note that each point has a unique id. Hence two points can never have same ids.
This sounds like you want to sort the list rather than use a comprehension.
new_points = sorted(points, key=lambda x:x.id)
The sorted function takes an iterable and a key function and returns a list. In this case the key function only needs to get the id.
I don't know of any way to populate random locations in a list with a one-liner. But if all you want is to be able to find a point by its id, you could use a dict in stead of a list:
new_points = {p.id: p for p in points}