'Python question, first if statement not running when bucket_name matches an item in bucket list

#1 Activates Boto for use and directs it to s3 storage

import boto3
s3 = boto3.resource('s3')

#2 Python ask user to create a bucket name

  bucket_name = input("Select a bucket name (must be all lowercase).  ")

#3 Python gathers bucket names within s3 and prints list

for bucket in s3.buckets.all():
    print(bucket.name)
bucket = list(s3.buckets.all())

#4 Checks bucket_name against the names with s3 to see if it matches any names, informs them if there is a match, and ask to create another name. If the name doesn't it create a new bucket with new unique name.

if bucket_name in bucket:
    print("The name you selected is already taken, please choose a different name")
    bucket_name = input('Select another bucket name (must be all lowercase).  ')
else:
    print('Your new bucket is named',bucket_name,"!")
    def create_bucket():
        s3_client = boto3.client('s3')
        s3_client.create_bucket(Bucket=bucket_name)
    create_bucket()


Solution 1:[1]

This should work:

import boto3

def create_bucket(bucket_name):
    s3_client = boto3.client('s3')
    s3_client.create_bucket(Bucket=bucket_name)

bucket_name = input("Select a bucket name (must be all lowercase).")

s3 = boto3.resource('s3')
all_buckets = list(s3.buckets.all())

if bucket_name in all_buckets:
    print("The name you selected is already taken, please choose a different name")
    bucket_name = input('Select another bucket name (must be all lowercase).  ')
else:
    print('Your new bucket is named',bucket_name,"!")
    create_bucket(bucket_name)

Solution 2:[2]

First extract all the buckets names with the following code.

import boto3
s3 = boto3.resource('s3')

bucket_name = input("Select a bucket name (must be all lowercase).  ")

all_buckets = [bucket.name.lower() for bucket in s3.buckets.all()]

Now check for the bucket_name present in it or not.

if bucket_name in all_buckets:
    print("The name you selected is already taken, please choose a different name")
    # Your rest of the logic goes here.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user215865
Solution 2