Interview Question: What is the difference between List and Dictionary in Python?


python Interview Question: What is the difference between List and Dictionary in Python? data structure interview questions python

python

This is a real interview question: What is the difference between List and Dictionary in Python?

You need to answer that immediately without googling..

My answer: a list is like an array whilst a dictionary stores key-value pairs.

The interviewer asked “is the dictionary ordered”?

What? I think he meant, can we trust the sequence when iterating the dictionary?

With some doubt, I still said: it is unordered.. because the dictionary in Python is like hash table and a hash table is clearly unordered.

He seems satisfied.

After I come back, I verified a little bit about this, first I created a list (or array) in Python3:

1
a=[1,2,3,4,5]
a=[1,2,3,4,5]

Remove item 3:

1
2
a.remove(3)
print(a) # [1, 2, 4, 5]
a.remove(3)
print(a) # [1, 2, 4, 5]

Put 3 back to the list:

1
2
a.append(3)
print(a) # [1, 2, 4, 5, 3]
a.append(3)
print(a) # [1, 2, 4, 5, 3]

So, yes, the list is ‘ordered’ because the new item always is appended to the end of the list. Let’s take a look at the dictionary.

1
a={1:1,2:2,3:3,4:4,5:5}
a={1:1,2:2,3:3,4:4,5:5}

Remove key=3:

1
a.pop(3) # {1: 1, 2: 2, 4: 4, 5: 5}
a.pop(3) # {1: 1, 2: 2, 4: 4, 5: 5}

Put key=3 back to the dictionary.

1
a[3] = 3
a[3] = 3

and we’ve got the original dictionary.

1
print(a) # a={1:1,2:2,3:3,4:4,5:5}
print(a) # a={1:1,2:2,3:3,4:4,5:5}

However, it is inconsistent on my friend’s PC, which shows {1:1,2:2,4:4,5:5,3:3}. So, the order cannot be trusted when you iterate the dictionary. The following code might break!

1
2
for key in a:
    do_something_with_order_matters(a[key])
for key in a:
    do_something_with_order_matters(a[key])

You may also like: 面经:Python 的 List 和 Dictionary 有啥区别?

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
382 words
Last Post: How to Set Voting Weight (using Python Script) for Minnows with Less than 500 Steem Power on Steemit?
Next Post: A Good-Content-Upvote SteemIt Bot for CN Community

The Permanent URL is: Interview Question: What is the difference between List and Dictionary in Python?

One Response

  1. Irene Hynes

Leave a Reply