Create an empty list in python with certain size

0 votes
I want to create an empty list (or whatever is the best way) that can hold 10 elements.

After that I want to assign values in that list, for example this is supposed to display 0 to 9:

s1 = list();

for i in range(0,9):

s1[i] = i

print s1

But when I run this code, it generates an error or in another case it just displays [] (empty).

Can someone explain why?
Aug 2, 2018 in Python by Priyaj
• 57,300 points
1,448 views

1 answer to this question.

0 votes

Try this instead:

lst = [None] * 10

The above will create a list of size 10, where each position is initialized to None. After that, you can add elements to it:

lst = [None] * 10

for i in range(10):

lst[i] = i

Admittedly, that's not the Pythonic way to do things. Better do this:

lst = []

for i in range(10):

lst.append(i)

Or even better, use list comprehensions like this:

[i for i in range(10)]

answered Aug 2, 2018 by bug_seeker
• 15,360 points

Related Questions In Python

0 votes
1 answer

Creating an empty list in Python

Here is how you can test which ...READ MORE

answered Aug 17, 2018 in Python by Priyaj
• 57,300 points
99 views
0 votes
1 answer

Is it possible to create an array with all values as zero in python?

You can use  np.zeros(4,3) This will create a 4 ...READ MORE

answered May 24 in Python by Anjali
67 views
+1 vote
4 answers

Count the frequency of an item in a python list

To count the number of appearances: from collections ...READ MORE

answered Oct 18, 2018 in Python by tinitales
2,211 views
0 votes
1 answer

Size of an object in Python

Use sys.getsizeof() function: >>> import sys >>> s = ...READ MORE

answered May 25, 2018 in Python by Nietzsche's daemon
• 4,260 points
40 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 425 views
+4 votes
6 answers
0 votes
1 answer

Difference between append vs. extend list methods in Python

append: Appends object at the end. x = ...READ MORE

answered Aug 8, 2018 in Python by bug_seeker
• 15,360 points
175 views
0 votes
1 answer

how to exit a python script in an if statement

This works fine for me: while True: ...READ MORE

answered Sep 19, 2018 in Python by bug_seeker
• 15,360 points
5,764 views