# make this bubble sort python code shorter than this? [closed]

i don't know if it can be made shorter than this

def bubble_sort(num):
for j in range((len(num)-1)):
for i in range((len(num)-1)):
if(num[i]>num[i+1]): num[i] , num[i+1] = num[i+1],num[i]
return num
print (bubble_sort(list(input("enter the array/list elements:"))))


## closed as unclear what you're asking by Wheat Wizard, user202729, Matthew Roh, xnor, Luis felipe De jesus MunozAug 5 '18 at 4:00

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

• If you want to ask others to make your code shorter, at least try to make your code already short. We don't want to post a trivial answer that says Remove unnecessary spaces around operators and Indent using only 1 space. – user202729 Aug 5 '18 at 3:10
• Also be explicit what you need, and what's the goal (tag it with tips, code-golf, and clarify whether it's byte count or character count; and what exactly is the requirement - the code can work differently while still satisfy the requirement) – user202729 Aug 5 '18 at 3:10
• Have you had a look at Tips for Golfing in Python? – Jo King Aug 5 '18 at 3:35
• Welcome to PPCG! You should at lleast refer to this and this question to try to golf your program more, currently there seems to be no effort made to golf it (ie. the most trivial golfs such as removing the print statement or removing superfluous whitespace). Additionally you might be interested in this answer. – ბიმო Aug 5 '18 at 3:36

I'm ignoring the function call right now and just golfing the function itself. I'm also assuming this is Python 2, since the original had a print statement rather than function.

## Shorten variable names, remove excess whitespace and brackets

### 116 bytes

def b(n):
for j in range(len(n)-1):
for i in range(len(n)-1):
if n[i]>n[i+1]:n[i],n[i+1]=n[i+1],n[i]
return n


Try it online!

## Change first for loop to repeat n times

### 102 bytes

def b(n):
for j in n:
for i in range(len(n)-1):
if n[i]>n[i+1]:n[i],n[i+1]=n[i+1],n[i]
return n


Try it online!

## Change if statement to one liner

### 98 bytes

def b(n):
for j in n:
for i in range(len(n)-1):n[i:i+2]=n[i:i+2][::(n[i]<n[i+1])*2-1]
return n


Try it online!

## Change for loop to exec

### 96 bytes

def b(n):exec"for i in range(len(n)-1):n[i:i+2]=n[i:i+2][::(n[i]<n[i+1])*2-1]\n"*len(n);return n


Try it online!

## Combine exec and for loop

### 94 bytes

def b(n):i=0;exec"n[i:i+2]=n[i:i+2][::(n[i]<n[i+1])*2-1];i+=1;i%=len(n)-1;"*len(n)**2;return n


Try it online!

• Just for the record, if j is unused then for j in [[]]*len(n) can be for j in n. – FryAmTheEggman Aug 5 '18 at 4:15
• Additionally, I could have then used sorted for 81 bytes – Jo King Aug 6 '18 at 10:10