-3

I have an existing list, e.g.

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]

len(months) would equal 6 in this example.

If I were to create an empty list of the same length as months, I'd use:

newList = [[] for i in months]

which would give me:

[[], [], [], [], [], []]

I want to create a new empty list that contains 1 item less than the original array. So that the length of the new array would be len(months) - 1

Ziyad Edher
  • 2,150
  • 18
  • 31
Nev Pires
  • 175
  • 1
  • 9
  • https://stackoverflow.com/questions/5205575/how-do-i-get-a-empty-array-of-any-size-i-want-in-python – Dennis Kuypers Mar 20 '18 at 22:14
  • 2
    Possible duplicate of [How do I get a empty array of any size I want in python?](https://stackoverflow.com/questions/5205575/how-do-i-get-a-empty-array-of-any-size-i-want-in-python) – Aran-Fey Mar 20 '18 at 22:15
  • `newList = [[] for i in months]` is not an empty list of length 6 - it is a list of 6 lists. There is no such thing as an empty list of length 6. An empty list has length 0. What are you really trying to do? – zvone Mar 20 '18 at 22:17
  • newList = [[] for i in range(len(months)-1)] – Liron Lavi Mar 20 '18 at 22:17
  • @zvone, you're right. I didn't explain myself correctly. It is creating a list of 6 lists. Instead, I want to create a list of 5 empty lists. I've basically created the list of 6, and then in another line, I've deleted one of the elements. – Nev Pires Mar 20 '18 at 22:22
  • Well, they you should just use `range(len(months)-1)` as others have suggested. But then again, think about what happens if `months` is empty... – zvone Mar 20 '18 at 22:25

1 Answers1

0

You can just remove 1 from the length of the months array.

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"] 
[[] for m in range(len(months)-1)]

Another option may be to use array slicing and negative indexing to get the first n-1 elements.

[[] for m in months[:-1]]
A. J. Parr
  • 7,731
  • 2
  • 31
  • 46