-1

I'm Doing this simple list to remove the elemen from the list depend on the the number that. i gave to it

mylist = ["apple", "banana", "cherry"]

ls =2
for i in range(0,ls):
    print(mylist[i])

print(mylist)

i wanna remove the other from the array and keen the rest depend on the ls if it 1 it will keep the first if it 2 it will keep the first two and so on

  • 2
    Have you tried [list slicing](https://www.learnbyexample.org/python-list-slicing/). Also take a look at a (boardly) [similar question](https://stackoverflow.com/questions/509211/understanding-slice-notation). – vyi Dec 07 '20 at 13:14
  • I want to know what you are trying to do .do you want to remove all the other element except the one whose inex you are passing?? – Sachin Rajput Dec 07 '20 at 13:16

4 Answers4

0

You can use list slicing. For example:

>>> mylist = ["apple", "banana", "cherry"]
>>> print(mylist[:2])
['apple','banana']

You can also create a new list with this method

>>> mylist = ["apple", "banana", "cherry"]
>>> my_second_list = mylist[:2]
>>> print(my_second_list)
['apple','banana']
Karol Adamiak
  • 141
  • 1
  • 9
0

You can simply use the slicing operator for this.

print(mylist[:ls])
ApplePie
  • 8,814
  • 5
  • 39
  • 60
0

Just do

ls = 2    # change this to what you want

mylist_cropped = mylist[:ls]
Philipp
  • 652
  • 2
  • 10
  • 28
0

I'm not sure that I really understand your question, but if you want to keep first n value in list you can try slicing

my_list = ["apple", "banana", "cherry"]

n = 1
my_list = my_list[:n]  # ["apple"]