I want to get a fixed length list from another list like:
a = ['a','b','c']
b = [0,0,0,0,0,0,0,0,0,0]
And I want to get a list like this: ['a','b','c',0,0,0,0,0,0,0]
. In other words, if len(a) < len(b)
, i want to fill up list a
with values from list b
up to length of the list b
, somewhat similar to what str.ljust
does.
This is my code:
a=['a','b','c']
b = [0 for i in range(5)]
b = [a[i] for i in b if a[i] else i]
print a
But it shows error:
File "c.py", line 7
b = [a[i] for i in b if a[i] else i]
^
SyntaxError: invalid syntax
What can i do?
Python Create List from 0 to 100. A special situation arises if you want to create a list from 0 to 100 (included). In this case, you simply use the list(range(0, 101)) function call. As stop argument, you use the number 101 because it's excluded from the final series.
Use the range() Function to Create a List of Numbers From 1 to N. The range() function is very commonly used in Python. It returns a sequence between two numbers given in the function arguments. The starting number is 0 by default if not specified.
The sum of an empty list, or a list filled with zeroes, is 0 which is Falsey. Alternatively if you're just scared about the zero division, you can skip all the conditionals and simply try it, excepting out the case where you might divide by zero. This is a common idiom in Python.
Why not just:
a = a + [0]*(maxLen - len(a))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With