DEV Community

Cover image for Python - Lists and loops
Flavio Campelo
Flavio Campelo

Posted on • Edited on

1 1

Python - Lists and loops

📮 Contact 🇧🇷 🇺🇸 🇫🇷

Twitter
LinkedIn


List

A list can hold many objects at the same time. So, you can make a list of students, cars, places or whatever you want.

Declaring a list

To declare a list you should use brackets [] to create a new list variable.

# an empty list...
emptyList = []
Enter fullscreen mode Exit fullscreen mode

If you want to create a new list with some objects, you should insert a comma to identify each of them.

# a list of fruits...
fruits = ["orange", "apple", "banana"]
print(fruits)

# OUTPUT: 
# ['orange', 'apple', 'banana']
Enter fullscreen mode Exit fullscreen mode

You can add new items any time to an existing list.

# appending new items to a list...
fruits.append("strawberry")
fruits.append("watermelon")

# OUTPUT: 
# ['orange', 'apple', 'banana', 'strawberry', 'watermelon']
Enter fullscreen mode Exit fullscreen mode

Picking up an element from a list

Elements from a list are index based. So, if you want to get the first element you should use 0, for the second one, 1 and so on.

# getting the first element from a list...
print (fruits[0])

# getting the third element from a list...
print (fruits[2])

# OUTPUT
# orange
# banana
Enter fullscreen mode Exit fullscreen mode

Checking if an element is present on a list

You can check if a element is on a list using writing a new if line (if element in list) like the example below.

fruit = 'pear'

if fruit in fruits:
  print(fruit + " is already on the list.")
else:
  print(fruit + " isn't on the list yet.")

# OUTPUT: 
# pear isn't on the list yet.
Enter fullscreen mode Exit fullscreen mode

Loop

A loop is used to run all over objets from a list.

Interacting with a loop

You can easly write a for lace (for element in list) to loop through all elements of your list.

# looping through all elements from my list...
for myFruit in fruits:
  print("I've added " + myFruit + " on my list.")

# OUTPUT:
# I've added orange on my list.
# I've added apple on my list.
# I've added banana on my list.
# I've added strawberry on my list.
# I've added watermelon on my list.
Enter fullscreen mode Exit fullscreen mode

Loop with range

Using range you can interact with a loop to display values from some criterias.

print("Range with element to stop. It'll take from the first until the third element...")
for i in range(3):
  print(i, end="-")
  print(fruits[i])

print("It'll take the 3 next elements starting from the second one...")
for i in range(1, 3):
  print(i, end="-")
  print(fruits[i])

print("It'll take the 3 next elements starting from the second one using step 1 between them...")
for i in range(1, 3, 1):
  print(i, end="-")
  print(fruits[i])

print("It'll take the 4 next elements starting from the first one and using step 2 between them...")
for i in range(0, 4, 2):
  print(i, end="-")
  print(fruits[i])

# OUTPUT
# Range with element to stop. It'll take from the first until the third element...
# 0-orange
# 1-apple
# 2-banana
# It'll take the 3 next elements starting from the second one...
# 1-apple
# 2-banana
# It'll take the 3 next elements starting from the second one using step 1 between them...
# 1-apple
# 2-banana
# It'll take the 4 next elements starting from the first one and using step 2 between them...
# 0-orange
# 2-banana
Enter fullscreen mode Exit fullscreen mode

Exiting from a loop

If you want to stop a loop, you can use break to exit from it

# It'll break when the fruit is "apple"...
for myFruit in fruits:
  print(myFruit)
  # if myFruit is apple, the loop will stop...
  if (myFruit == "apple"):
    break # It stops the loop...

# OUTPUT
# orange
# apple
Enter fullscreen mode Exit fullscreen mode

Typos or suggestions?

If you've found a typo, a sentence that could be improved or anything else that should be updated on this blog post, you can access it through a git repository and make a pull request. If you feel comfortable with github, instead of posting a comment, please go directly to https://github.com/campelo/documentation and open a new pull request with your changes.

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

If this article connected with you, consider tapping ❤️ or leaving a brief comment to share your thoughts!

Okay