简体   繁体   中英

skip first and last item in the list in python?

iplist = ['1.1.1.1', '2.2.2.2', '3.3.3.3', '4.4.4.4', '5.5.5.5']

How do i skip first ,last entry and run a for loop in items between ? I am aware of skipping first([1:]) and last([:-1]) separate but not together.

You can use -ve slicing -> Skip 1st element & last element

iplist[1:-1]

For loop will look like this:

for i in iplist[1:-1]:
    print(i)

Output will be:

2.2.2.2 
3.3.3.3
4.4.4.4

Got the answer:

for ip in iplist[1:][:-1]:
 #Do stuff

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM