You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中arr = [-1]*n语句的含义与执行结果咨询

Understanding arr = [-1]*n in Python

Hey there! Let me break down this Python syntax clearly—it’s a handy list creation trick that’s used all the time, so I’m glad you asked about it.

What the syntax means

This is Python’s list multiplication feature. Here’s the simple breakdown:

  • [-1] is a single-element list holding the integer -1
  • The * operator, when paired with a list and an integer n, generates a new list by repeating the original list exactly n times

What arr contains after execution

The resulting arr will be a list with n sequential copies of -1. For example:

  • If n = 4, arr becomes [-1, -1, -1, -1]
  • If n = 0 or n is a negative integer, arr will be an empty list []

A quick heads-up for edge cases

This works flawlessly for immutable elements like integers, strings, or tuples. But if you try this with a mutable element (like another list, e.g., arr = [[]]*n), all the "copies" will reference the same underlying object—changing one will alter all of them! Since you’re using -1 here though, you don’t have to worry about that tricky gotcha.

内容的提问来源于stack exchange,提问作者RothX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:11:11