1

Why do method 1 and method 2 not print the same output?

>>> names = ["Apple", "Samsung", ]

# Method 1/Print the first item in names
>>> print(names[:1])
['Apple']

# Method 2/Print the first item in names
>>> print(names[0])
Apple
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Hassan C
  • 15
  • 2

1 Answers1

3

Slicing syntax (Method 1) always produces a new list, even if the new list has only one item.

Indexing (Method 2) produces the item at that position in the iterable.

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
  • I think this is definately adequately explained in the dupe, e.g. this answer https://stackoverflow.com/a/4729334/6260170 – Chris_Rands Mar 13 '19 at 19:30
  • @Chris_Rands The question was not "explain slice notation". It's not clear the OP knew it was *called* slice notation. – Mark Tolonen Mar 13 '19 at 19:33
  • @Chris_Rands I do know a few things about slicing but actually I have never learned it deeply. Generally, problems like these confuse me so much. – Hassan C Mar 13 '19 at 20:11
  • I didn't downvote the OP but it's clearly a dupe, the answer i linked to even says "indexing gives items, not list" and "Slicing gives lists" – Chris_Rands Mar 13 '19 at 21:17