Questions About Python List

Asked 2 months ago, Updated 2 months ago, 1 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.

python

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.
Note:
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.

https://docs.python.org/ja/3.8/library/stdtypes.html#sequence-types-list-tuple-range
According to the reference
s[i:j]=t
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')
lis


2022-09-30 11:08

If you have any answers or tips


© 2022 OneMinuteCode. All rights reserved.