# Lists and Loops

&#x20;The code below shows some ways of using python **lists** (known as **arrays** in many languages). Note how these lists are "sliced" from index i to j using `my_list[i:j]` notation.

## How to print a list structure

my\_list = \[1, 2, 3, "a", "b", "c"] print("my\_list is:", my\_list)

```python
my_list is: [1, 2, 3, 'a', 'b', 'c']
```

## Prints each element of a list individually

```python
print("Looping through a list...")
    for item in my_list:
    print("item is", item)
```

```
Looping through a list...
item is 1
item is 2
item is 3
item is a
item is b
item is c
```

## Using range to loop through a list by index

```python
print("A less great way to loop through a list...")
    for index in range(len(my_list)):
    item = my_list[index] # accessing an element in a list! print("item is", item)
```

```python
A less great way to loop through a list...
item is 1
item is 2
item is 3
item is a
item is b
item is c
```

## List slicing

![](https://856544863-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LWmV4m0fRjbhKVvUBcH%2F-LWmagGAY7tBIVNP30lZ%2F-LWmc9MKaHDkDVuV_ZOw%2Fimage.png?alt=media\&token=e07d29c7-edb0-41dc-a0a9-6784c879a228)

## Looping through a partial list

```python
print("Slicing a list from beginning...") 
    for item in my_list[:3]: 
    print("item is", item)
```

```python
item is 1
item is 2
item is 3
```

## Looping through a partial list again

```python
print("Enumerating a list...") 
    for i, item in enumerate(my_list):
    print("item number", i, "is", item)
```

```python
Slicing a list to the end...
item is 1
item is 2
item is 3
item is a
item is b
item is c
```

```python
print("Another way to enumerate using a list 'method'...")
for item in my_list: 
     index = my_list.index(item)
     print("item", item, "has index", index)
```

```python
Another way to enumerate using a list 'method'...
item 1 has index 0
item 2 has index 1
item 3 has index 2
item a has index 3
item b has index 4
item c has index 5
```
