10

Is it possible to assign a list with empty values in Python?
This is possible:

x = []

But I want to do something like:

x = [4,7,2, ,8,9,1]

with an empty value inside. The reason is that I have a large number of lists with 7 values and sometimes one of the values are unavailable. I need to keep say 8 as x[4],9 as x[5] etc.

My thoughts:
Maybe I should just put a number like 999 inside, or a string "empty" and tell my code to ignore 999 or "empty" or whatever.

What is the best option here?

1
  • 3
    You seem to be using the list as proxy for a mapping of integer keys, rather than as an ordered sequence. Consider using a dictionary { 0: 4, 1: 7, 2: 2, 4: 8, 5: 9, 6: 1} instead. Commented Oct 6, 2014 at 15:58

3 Answers 3

28

Use None for the "empty" value.

a = [1,2,3,4,5]
b = [11,22,None,44,55]
Sign up to request clarification or add additional context in comments.

1 Comment

Will None return the value “None,” or indicate to the program that there’s no value and return no value at all? Also, would it be written as shown, with no “” or ‘’? Or should it be in quotes like a string? I’ve run into trouble trying to use variables in a list. Just wondering if python will recognize None as an established value or will attempt to evaluate it as a variable.
3

Another option other than using None is to use some other unique object such as empty = object() as this allows None to be used as a list item and then test if the list item is empty via l[x] is empty.

Comments

1

Use "None". It indicates that there is no value.

2 Comments

how is this different to rusticbit's answer?
Sorry, I didn't see that there was an answer already when I put mine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.