It looks like you're using Internet Explorer 11 or older. This website works best with modern browsers such as the latest versions of Chrome, Firefox, Safari, and Edge. If you continue with this browser, you may see unexpected results.

# Python for Basic Data Analysis: 1.15 For loops

Get started on your learning journey towards data science using Python. Equip yourself with practical skills in Python programming for the purpose of basic data manipulation and analysis.

## For loops

#### for  loops in a list

With the  for  loop, we can execute a set of statements - once for each item in a list, tuple, set etc.

Syntax

```fruits = ["apples", "bananas", "cherries"]
for x in fruits:
print(x)
```

This shows that a  for  loop iteration is made, and it runs through each item in the list called fruits.

Here, the x refers to a temporary variable used to store the value of the current position in the range of the for loop that only has scope within its for loop. You could use any other variable name in place of "i" such as "count" or "x" or "number".

Below, i used fruit as the temporary variable instead of x.

```fruits = ["apples", "bananas", "cherries"]
for fruit in fruits:
print(x)
```

Examples

#### for  loops in a string

Even strings are iterable objects as they contain a sequence of characters.

Syntax

```for x in banana:
print(x)
```

Example

#### for  loops with  breaks

With the  break  statement, we can stop the loop before it loops through all the items.

Syntax

```fruits = ["apples", "bananas", "cherries"]
for x in fruits:
print(x)
if x == "bananas":
break
```

Examples

#### for  loops with  continue

With the  continue  statement, we can skip over a part of the loop where an additional condition is set, and then go on to complete the rest of the loop.

Syntax

```fruits = ["apples", "bananas", "cherries"]
for x in fruits:
if x == "bananas":
continue
print(x)
```

Examples

## Exercises

1. Create a list containing 5 names and use the  for  loop to print out all the names

2. Use the same list from number 1, use  break  to stop after the third element.

3. Iterate the string "hullaballoo". Use  continue  to skip all the letter 'l', and print the rest.