简体   繁体   中英

Python For Loops has a colon between two numbers

What exactly does a for loop with a colon instead of a comma do? I have a list and a for loop printing all of the items in the list. Sorry if this is really simple but I have attempted finding an answer online and I am somewhat new to Python.

import requests from bs4 import BeautifulSoup

page = requests.get("https://talksport.com/football/572055/") soup = BeautifulSoup(page.content, 'html.parser')

clubs = soup.findAll("h3")

for club in clubs[17:-2]:
   # do something

The colon has nothing to with the for loop, it's just slicing a list. I will give you an example.

Let's say you have a list like this:

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

When you slice the list, you get only the part of the list you ask for, for example:

my_list[0] # This is the first element of the list
my_list[-1] # This is the last element of the list

You can combine these with a colon like this:

my_list[2:5] # The elements between index 2 and 5

In this case, that would be

[3, 4, 5]

In your specific case,

clubs[17:-2] # The elements between index 17 and the second to last index.

Since I don't know what is in your list I will give a similar example with my list:

my_list[4:-2]

Which returns

[5, 6, 7, 8]

Hope it helps:)

EDIT: And just to make sure I answer what you ask, slicing the list in the loop just changes which elements go into your for loop.

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