Questions About Python List

Asked 5 months ago, Updated 5 months ago, 9 views

I'm new to Python.

list=['a', 'i', 'u', 'e', 'o']
list [1:4] = ['a']

If so,

 ['a', 'a', 'a', 'e', 'o']

I thought it would be

 ['a', 'a', 'o']

The length has become shorter.
I would appreciate it if you could tell me what the difference is.


2022-09-30 11:08

3 Answers

The list in Python is called dynamic-array in other languages.
Because the size changes dynamically, the behavior in the question is normal.
Data Structure:About List Types

If you want to fix the length, you have to choose such a data structure.

import numpy as np
arr = np.array (['a', 'b', 'c', 'd', 'e'])
arr[1:4] = 'a'

# array('a', 'a', 'a', 'a', 'e', dtype='<U1')

With a standard package, it might be possible (maybe) with array

Also, you should not use the same name as Python's basic data type, such as list or dict.
(For example, lstdct)

2022-09-30 11:08

Assigning to a slice will change the length of the list.
According to the reference
Replace the i through jth slice of s with the contents of the itable t

It says "replace".

2022-09-30 11:08

By the way, if you want to rewrite it in detail, you can write it like this.

 lis=['a', 'i', 'u', 'e', 'o']
delis [1:3]
lis.insert(1, 'a')
lis.insert(2, 'a')

2022-09-30 11:08

If you have any answers or tips

© 2023 OneMinuteCode. All rights reserved.