Python List: Why do we create two types of empty lists some times?

Hi all,

I have been struggling to understand the differences in creating a new list that some times is empty [ ] or some times it as a zero in it [0]?


test_list = [ ]

vs

test_list = [0]


Can someone please explain the rationale behind setting it to 0 or nothing?

my understanding so far is that if it is empty [ ], that means we do not want to specify any type of input for the list, and when we put a [0], then we treat it as index for later referencing or we want the list to begin at index 0?

Hi @sharknaut,

How we initialize a list depends on its purpose.

If we create a list for accumulating items that meet specified criteria, we usually initialize it as an empty list, then add items that meet those criteria. Following is an example:

numbers = [2, 3, 5, 7, 9, 6, 8]
# list for numbers divisible by three
divisible_by_three = []
for number in numbers:
  if number % 3 == 0:
    divisible_by_three.append(number)
print(divisible_by_three)

Output:

[3, 9, 6]

So that we can discuss a list that we initialize with a 0 in it, please post an example of pertinent code, or provide us with a link to an exercise that offers such an example.

Thank you appylpye,

great explanation for empty list.

the [ 0 ] example one of it is in this example:
Max Num Challenge

code:

#Write your function here
def max_num(nums):
  maximum = nums[0]
  for number in nums:
    if number > maximum:
      maximum = number
  return maximum

#Uncomment the line below when your function is done
print(max_num([50, -10, 0, 75, 20]))

your original question:

test_list = [ ]

# vs

test_list = [0]

should have been:

test_list = [ ]

# vs

test_list[0]

those things are very different, test_list = [] will create a new list, while test_list[0] will access the first element (at index 0) of an test_list

once a list has been defined, we can access elements in the list by index (position)

You are right, I did notice this myself just now.

Thank you for pointing it out, it makes more sense now in these exercises.

This topic was automatically closed 18 hours after the last reply. New replies are no longer allowed.