1

How do I go about getting an empty list that looks like this:

[..........]

Where I can place items in place of the dots and return the number of items. The list is supposed to represent positions of items. For example

[..V....K..]

When I use None. I just get a string back with None in every slot.

Blue
  • 51
  • 4

1 Answers1

0

There's nothing stopping you from using None, but you could use '.' as well. If your length is n:

x = ['.'] * n

or:

x = ['.' for _ in range(n)]

which is probably better practice.

chuck
  • 1,420
  • 4
  • 19
  • the first approach is faster and I would say a better practice, why you think the second approach is better? using list comprehension? – kederrac Mar 07 '20 at 16:25
  • The first approach creates multiple references to the same object, while the second creates multiple objects, which is why the first is fatser. This doesn't matter with `None` since it isn't an object, but if you create a list of actual objects with the first method and then change one of them, they will all change since they are just references. This very often causes weird bugs that are hard to find – chuck Mar 07 '20 at 16:34
  • Yes, but if the inner object is not mutable that's not an issue since it can't be changed anyway. This only might be a problem when it is mutable – chuck Mar 07 '20 at 16:37
  • No, you don't. Try creating a list of lists using the first method, and then changing one list. All of the lists will be changed – chuck Mar 07 '20 at 16:46
  • I was saying not mutable objects, the list is a mutable object – kederrac Mar 07 '20 at 16:48
  • But when I do that and print it out I get [None, None, None, None]. When I want [.....] – Blue Mar 07 '20 at 17:10
  • Oh I thought you wanted `None` because of what you wrote at the end. I updated it to be '.' – chuck Mar 07 '20 at 17:14