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
• 58,090 points
27,753 views
s1 = list();
for i in range(0,9):
   s1 += str(i)

print(s1)

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)]

Hope this will help!

If you need to know more about Python, join Python certification course online today.

Thanks!

answered Aug 2, 2018 by bug_seeker
• 15,520 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
• 58,090 points
890 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, 2019 in Python by Anjali
858 views
+1 vote
8 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
35,179 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
792 views
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,023 views
0 votes
1 answer
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,790 points
3,420 views
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,520 points
1,936 views
0 votes
5 answers

how to exit a python script in an if statement

Instead of using the normal UTF-8 encoding, ...READ MORE

answered Jul 4, 2023 in Python by bodymist
• 140 points
348,544 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP