Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,990 questions

51,935 answers

573 users

How to slice a list in Python

5 Answers

0 votes
lst = [1, 5, 3, 6, 5, 7, 8, 9]

slc = lst[1:4]

print(slc)
 
 
'''
run:
 
[5, 3, 6]
 
'''

 



answered Nov 3, 2018 by avibootz
0 votes
lst = [1, 5, 3, 6, 5, 7, 8, 9]

slc = lst[3:-1]

print(slc)
 
 
'''
run:
 
[6, 5, 7, 8]
 
'''

 



answered Nov 4, 2018 by avibootz
0 votes
lst = [1, 5, 3, 6, 5, 7, 8, 9]

slc = lst[:2]

print(slc)
 
 
'''
run:
 
[1, 5]
 
'''

 



answered Nov 4, 2018 by avibootz
0 votes
lst = [1, 5, 3, 6, 5, 7, 8, 9]

slc = lst[4:]

print(slc)
 
 
'''
run:
 
[5, 7, 8, 9]
 
'''

 



answered Nov 4, 2018 by avibootz
0 votes
lst = ["python", "c", "java", "c++", "php", "c#"]
 
first_three = lst[0:3]
print(first_three)
 
first_two = lst[:2]
print(first_two)
 
all_but_last_two = lst[:-2]
print(all_but_last_two)
 
second_and_third = lst[1:3]
print(second_and_third)
 
every_second = lst[::2]
print(every_second)

last = lst[-1]
print(last)


 
 
'''
run:
 
['python', 'c', 'java']
['python', 'c']
['python', 'c', 'java', 'c++']
['c', 'java']
['python', 'java', 'php']
c#
 
'''

 



answered Apr 28, 2024 by avibootz

Related questions

...