-2

I was trying bubble sort through define function method but it keeps on showing attribute error. I am not able to understand the reason, so if anyone could explain this error it would be a great help.

l=[1,4,7,9,0]

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

print(b)
8
  • 2
    What do you expect l.kono() to mean? Commented Apr 9, 2021 at 12:51
  • that it will execute that function i created Commented Apr 9, 2021 at 12:53
  • 1
    That isn't how you call functions in Python -- it is how you call methods -- but this definition isn't of a method. Commented Apr 9, 2021 at 12:53
  • 2
    Change the function definition to def kono(l) and the call to kono(l). Commented Apr 9, 2021 at 12:54
  • 1
    What is your expected output? Commented Apr 9, 2021 at 12:56

2 Answers 2

1

Change your code so that the function takes a list; then, to call it, use kono(l) instead of l.kono(); then there's no need to assign the result to b since the list is passed as a reference (also the function doesn't return any value):

l=[1,4,7,9,0]

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

print(l)
Sign up to request clarification or add additional context in comments.

4 Comments

ohh so do you mean that when i was calling the result to b the value was not being assigned to it
There is no return statement in your function, so assigning values to it will always result in None values. In Python lists (and objects in general) are passed as reference, so changing them inside the function will cause them to also change outside.
@ altermetax , I write this simple code :def summ(a,b): c = a + b a = 3 b = 5 summ(a,b) print(a,b) but the output is 3,5
Numbers are immutable objects, so you do need to return those if you need the value.
0

If you want you can add a return. All depends on how you want to define your function

l=[1,4,7,9,0]

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

b = kono(l)

print('This is b',b)
#Output: This is b [0, 1, 4, 7, 9]

In this case, you will assign the ordered list to b.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.