Python List Function Question

Asked 2 years ago, Updated 2 years ago, 153 views

1.

def random_pop(data):
    number = random.randint(0, len(data)-1)
    return data.pop(number)

2.

def random_pop(data):
    number = random.choice(data)
    data.remove(number)
    return number

These two functions return the same value Why can't we express function number 2 as follows?

default_pop(data):
    number = random.choice(data)
    return data.pop(number)

python list pop

2022-09-22 16:57

1 Answers

The x value in pop(x) must be an index value.

>>> a = [1, 2, 3, 'a', 'b', 'c']
>>> a.pop(4)
'b'
>>> a
[1, 2, 3, 'a', 'c']

There is a big difference between the input value and the remove function that deletes the value as an element.

>>> a = [1, 2, 3, 'a', 'b', 'c']
>>> a.remove('a')
>>> a
[1, 2, 3, 'b', 'c']


2022-09-22 16:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.