3
list = [1, 6, 5, 7, 8]
num = int(input("Enter a value") #lets say 3 for now

How do I get the values from the start of the list to the num?

Output should be:

[1, 6, 5] 
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Eren145
  • 79
  • 1
  • 8
  • 3
    Does this answer your question? [Python: Fetch first 10 results from a list](https://stackoverflow.com/questions/10897339/python-fetch-first-10-results-from-a-list) – Tomerikoo Jan 24 '20 at 03:51
  • it does. Thanks to all who answered – Eren145 Jan 24 '20 at 04:29

3 Answers3

7

You can use slicing. Slicing allows you to take a certain range of numbers from a list.

list = [1, 6, 5, 7, 8]
num = int(input("Enter a value")

print(list[0:num])

That should return : [1,6,5]

Hope that helps!

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • oh ok. Just a small side question though. When you wrote : list[0:num], does the 0:num always have to be in those brackets? ( [ ] ) – Eren145 Jan 24 '20 at 03:57
  • 2
    @Eren145 As for as my python knowledge goes, Im pretty sure that it needs to be in those brackets. That's the correct syntax for slicing. You can learn more about slicing and lists here: https://docs.python.org/3/tutorial/introduction.html#lists – ScarletCoder16 Jan 24 '20 at 03:59
1

You can achieve this in a single line of code,

data = [1, 6, 5, 7, 8]
print(data[:int(input('Enter the number'))])
Afnan Ashraf
  • 174
  • 1
  • 14
  • 2
    It's just a slicing mechanism in python. if you want to get a range of items from a list You can use slicing mechanism. Here I am passing the integer getting from the input to the list slicing. data[:] will get the all items from the list just like an exact copy of the list. if you pass the input as 3 then it will give you a new list of items from position 0th index to the 3rd index. – Afnan Ashraf Jan 24 '20 at 03:52
0

list[:3]

You can use slicing to achieve this. Note: Don't name your list list! Please name it something else, as you will not be able to call list() anymore.

PacketLoss
  • 5,561
  • 1
  • 9
  • 27