0

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

All the integers in this array can be converted into strings individually in the following 3 ways.

1) Using Str

a=[1,2,3,4,5]
for i in range(len(a)):
    a[i] = str(a[i])
print(type(a[0]))

2) Using Map

a=[1,2,3,4,5]
a = list(map(str,a))
print(type(a[0]))

3) Using List Comprehension

a=[1,2,3,4,5]
a = [str(i) for i in a]
print(type(a[0]))

Can I know what is the time complexity in all the 3 cases to find out which method is efficient? I am a bit confused about this.

Thanks in advance!

  • Please see [Why not upload images of code on SO when asking a question?](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-on-so-when-asking-a-question) first. – Amadan Sep 30 '19 at 07:41
  • @Amadan, Thanks for letting me know, I have edited the same – user2978343 Sep 30 '19 at 07:56
  • 2
    What is the difference between (1) and (3)? Also, the time complexity is exactly the same: O(N). – Amadan Sep 30 '19 at 07:57
  • @Amadan, there was a mistake in the edit, I have now edited them properly. 1 and 3 are different snippets now – user2978343 Sep 30 '19 at 08:04
  • 1
    Still same O(N). – Amadan Sep 30 '19 at 08:05
  • regarding `range(len(list))`, check [this SO post](https://stackoverflow.com/q/19184335/10197418). otherwise, besides time complexity, it's sometimes a good idea to use `timeit` to check the performace of different options that give the same result. – FObersteiner Sep 30 '19 at 08:12
  • @Amadan, I have another general query...... When I insert some elements in the dictionary, it automatically gets sorted....so, for inserting n elements the time complexity is O(n) or O(nlogn)? – user2978343 Sep 30 '19 at 08:13
  • https://wiki.python.org/moin/TimeComplexity#dict — amortised cost is O(1) per single dict insert. – Amadan Sep 30 '19 at 08:16

0 Answers0