2
s = "text"
parts = [] # <<< why not just parts = 0
print id(parts) # 3074379948

parts = s.split()
print id(parts) # 3074380332

I saw this in several programs, but I can't undestand why. Because parts reference to different objects. So this is just for readabillity?

2
  • I'd say parts = [] is better than parts = 0. It shows that parts is a list, even if it's the redefined later as a different list. Using parts = 0 first would just add extra confusion as the type would be changed. Commented May 2, 2015 at 16:44
  • 1
    It may matter if s.split() raises an exception - in finally routine parts is always defined and is always a 'right' type. In your code snippet - it does not make any sense. Commented May 2, 2015 at 16:44

2 Answers 2

3

If you look at the second part of the code, you see that the assignment that is happening is

parts = s.split()
print id(parts) # 3074380332

In the above, parts is expected to be a list, since it is the output of .split. It would thus be logical, to instantiate it with a value of the same kind, like parts = [], for maintaining coherence of the program.


Imagine a scenario, where the second part fails (example code), and you still want to do something with parts. If you instantiate this with any other value, your code becomes inconsistent logically, and may throw errors. If you did parts = 0 below, it simply would've failed since then parts would not have been an iterable, and so on:

parts = [] # works
# parts = 0 # doesn't work
try:
    s = 0
    parts = s.split()
except:
    pass
for part in parts:
    print part
Sign up to request clarification or add additional context in comments.

Comments

2

The code is setting a default value, where the parts value is expected to be a list object, always.

Perhaps the parts = s.split() line is not always reached, but the parts variable is always used and expected to be a list. This could happen if there is an if statement, or a try..except or try..finally statement, or even in a loop where a continue or break statement will bypass part of the loop body.

It makes no sense to then set parts = 0, because an integer is not the same type of object. If the s.split() is always executed, you can omit the parts = [] line altogether, it is then just redundant.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.