Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to fill a list with 0 using python

Tags:

python

list

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?

like image 421
zjm1126 Avatar asked Oct 18 '22 05:10

zjm1126


People also ask

How do you make a list 0 100 in Python?

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.

How do you make a list of numbers from N to 0 in Python?

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.

Is 0 A valid list in Python?

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.


1 Answers

Why not just:

a = a + [0]*(maxLen - len(a))
like image 113
Achim Avatar answered Oct 19 '22 17:10

Achim