-3

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
Feodoran
  • 1,752
  • 1
  • 14
  • 31
sam__pyle
  • 3
  • 3
  • 4
    Please show us some code and what you've tried so far – Adam Boinet Jun 03 '20 at 10:57
  • Please give [examples](https://stackoverflow.com/help/minimal-reproducible-example]) – Raghul Raj Jun 03 '20 at 10:59
  • You mean the `clubs[17:-2]`? This is nothing directly related to loops, but a way to only select certain parts of the sequence `clubs`. This is called *slicing*. – Feodoran Jun 03 '20 at 11:08
  • Does this answer your question? [Understanding slice notation](https://stackoverflow.com/questions/509211/understanding-slice-notation) – Feodoran Jun 03 '20 at 11:13
  • I think you should check [this](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-on-so-when-asking-a-question). – Adam Boinet Jun 03 '20 at 11:14

1 Answers1

1

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.

Fredrik Nilsson
  • 549
  • 4
  • 13