Index and Lists - Index out of rangeHow do I check if a list is empty?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonAccessing the index in 'for' loops?How to make a flat list out of list of lists?How do I get the number of elements in a list in Python?How do I concatenate two lists in Python?How to clone or copy a list?How do I list all files of a directory?Why not inherit from List<T>?
How can I fix this gap between bookcases I made?
How is the claim "I am in New York only if I am in America" the same as "If I am in New York, then I am in America?
Why is this code 6.5x slower with optimizations enabled?
How did the USSR manage to innovate in an environment characterized by government censorship and high bureaucracy?
What would the Romans have called "sorcery"?
How long does it take to type this?
How to make payment on the internet without leaving a money trail?
Why Is Death Allowed In the Matrix?
Why is an old chain unsafe?
Why has Russell's definition of numbers using equivalence classes been finally abandoned? ( If it has actually been abandoned).
Is it tax fraud for an individual to declare non-taxable revenue as taxable income? (US tax laws)
Is it possible to do 50 km distance without any previous training?
Can a German sentence have two subjects?
My colleague's body is amazing
Copenhagen passport control - US citizen
Japan - Plan around max visa duration
How is it possible for user's password to be changed after storage was encrypted? (on OS X, Android)
Why doesn't Newton's third law mean a person bounces back to where they started when they hit the ground?
Is it possible to make sharp wind that can cut stuff from afar?
Why is the design of haulage companies so “special”?
How does one intimidate enemies without having the capacity for violence?
Motorized valve interfering with button?
What typically incentivizes a professor to change jobs to a lower ranking university?
"which" command doesn't work / path of Safari?
Index and Lists - Index out of range
How do I check if a list is empty?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonAccessing the index in 'for' loops?How to make a flat list out of list of lists?How do I get the number of elements in a list in Python?How do I concatenate two lists in Python?How to clone or copy a list?How do I list all files of a directory?Why not inherit from List<T>?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
Shouldn't the following code print? 100 100
price = 100 # assigns 'price' reference to 100
price = [price] # creates a 'price' list with 1 element: [100]
for i in range(1, 3):
print(price[0]) # prints 100
price[i] = price[i - 1]
price.append(price[i])
print(price[i])
Getting a IndexError: list assignment index out of range
error at line price[i] = price[i - 1]
, but the line right before prints 100
successfully. Shouldnt price[i] simply be getting assigned price[0] value?
python list
add a comment |
Shouldn't the following code print? 100 100
price = 100 # assigns 'price' reference to 100
price = [price] # creates a 'price' list with 1 element: [100]
for i in range(1, 3):
print(price[0]) # prints 100
price[i] = price[i - 1]
price.append(price[i])
print(price[i])
Getting a IndexError: list assignment index out of range
error at line price[i] = price[i - 1]
, but the line right before prints 100
successfully. Shouldnt price[i] simply be getting assigned price[0] value?
python list
Issue is when trying to access python[i], then it throws index out of range. Left statement is not evenevaluated
– Apolozeus
Mar 22 at 0:42
You're trying to append items to a list, see below. You can't just assign a value at nonexistent index positions and expect the list to automatically append or grow itself.
– smci
Mar 22 at 0:58
1
(Btw if you know a priori the list will have at least 3 elements, you could initialize it toprice = [None] * 3
and you get[None, None, None]
. Now you can directly assign to them. But, explicitly doing append is better practice.)
– smci
Mar 22 at 1:01
add a comment |
Shouldn't the following code print? 100 100
price = 100 # assigns 'price' reference to 100
price = [price] # creates a 'price' list with 1 element: [100]
for i in range(1, 3):
print(price[0]) # prints 100
price[i] = price[i - 1]
price.append(price[i])
print(price[i])
Getting a IndexError: list assignment index out of range
error at line price[i] = price[i - 1]
, but the line right before prints 100
successfully. Shouldnt price[i] simply be getting assigned price[0] value?
python list
Shouldn't the following code print? 100 100
price = 100 # assigns 'price' reference to 100
price = [price] # creates a 'price' list with 1 element: [100]
for i in range(1, 3):
print(price[0]) # prints 100
price[i] = price[i - 1]
price.append(price[i])
print(price[i])
Getting a IndexError: list assignment index out of range
error at line price[i] = price[i - 1]
, but the line right before prints 100
successfully. Shouldnt price[i] simply be getting assigned price[0] value?
python list
python list
edited Mar 22 at 1:39
Patriots299
asked Mar 22 at 0:31
Patriots299Patriots299
16211
16211
Issue is when trying to access python[i], then it throws index out of range. Left statement is not evenevaluated
– Apolozeus
Mar 22 at 0:42
You're trying to append items to a list, see below. You can't just assign a value at nonexistent index positions and expect the list to automatically append or grow itself.
– smci
Mar 22 at 0:58
1
(Btw if you know a priori the list will have at least 3 elements, you could initialize it toprice = [None] * 3
and you get[None, None, None]
. Now you can directly assign to them. But, explicitly doing append is better practice.)
– smci
Mar 22 at 1:01
add a comment |
Issue is when trying to access python[i], then it throws index out of range. Left statement is not evenevaluated
– Apolozeus
Mar 22 at 0:42
You're trying to append items to a list, see below. You can't just assign a value at nonexistent index positions and expect the list to automatically append or grow itself.
– smci
Mar 22 at 0:58
1
(Btw if you know a priori the list will have at least 3 elements, you could initialize it toprice = [None] * 3
and you get[None, None, None]
. Now you can directly assign to them. But, explicitly doing append is better practice.)
– smci
Mar 22 at 1:01
Issue is when trying to access python[i], then it throws index out of range. Left statement is not even
evaluated
– Apolozeus
Mar 22 at 0:42
Issue is when trying to access python[i], then it throws index out of range. Left statement is not even
evaluated
– Apolozeus
Mar 22 at 0:42
You're trying to append items to a list, see below. You can't just assign a value at nonexistent index positions and expect the list to automatically append or grow itself.
– smci
Mar 22 at 0:58
You're trying to append items to a list, see below. You can't just assign a value at nonexistent index positions and expect the list to automatically append or grow itself.
– smci
Mar 22 at 0:58
1
1
(Btw if you know a priori the list will have at least 3 elements, you could initialize it to
price = [None] * 3
and you get [None, None, None]
. Now you can directly assign to them. But, explicitly doing append is better practice.)– smci
Mar 22 at 1:01
(Btw if you know a priori the list will have at least 3 elements, you could initialize it to
price = [None] * 3
and you get [None, None, None]
. Now you can directly assign to them. But, explicitly doing append is better practice.)– smci
Mar 22 at 1:01
add a comment |
5 Answers
5
active
oldest
votes
If you are just trying to append to a list, trying to do that with an index won't exactly work because that index isn't present in the list:
somelist = []
somelist[0] = 1
IndexError
So just use append
for i in range(1,3):
price.append(price[i-1])
add a comment |
You're trying to append items to a list, or more precisely to initialize a list with repeated copies of something. Here are Pythonic ways to do that:
# Use a list comprehension
>>> price = [100 for _ in range(3)]
[100, 100, 100]
# Use itertools.repeat
>>> import itertools
>>> list(itertools.repeat(100, 3))
[100, 100, 100]
These are both faster than (repeatedly) doing append()
, which is O(N), so repeatedly doing append()
is O(N^2) on a long list, which gets very slow.
(Btw if you know a priori the list will have at least N elements, and N is large, you could initialize it to price = [None] * N
and you get [None, None, None...]
. Now you can directly assign to them. But, explicitly doing append is better practice for beginners.)
add a comment |
The problem is you are assigning at an index too great for the length of the array.
for i in range(1, 3):
This initializes i to 1. Since arrays are zero-indexed, and the length of your array is 1 on the first pass, you will hit an assignment out of range error
at the line you mentioned (when i=1
).
Here is a minimal example showing the issue:
my_array = ["foo"]
my_array[1] = "bar" # throws assignment out of range error
add a comment |
You can't assign a value to a list directly why this list has note a previous size defined. You have to use append to add elements to the position you want.
Check:
# Check the value on our initial position
print(price[0])
for i in range(1, 3):
price.append(price[i-1])
print(price[i])
add a comment |
That will not print out:
100
100
You initialized a list with 1 element, the size of that list is 1. However your range starts at 1 for the for
loop , what's really happening is:
price = 100 # assigns 'price' to 100
price = [price] # creates a 'price' list with 1 element: [100]
for i in range(1, 3): # The list is 0-indexed, meaning price[0] contains 100
print(price[0]) # prints 100 as it should
price[i] = price[i - 1] # i is 1, price[i] is not an assigned value, i.e: you never assigned price[1]
price.append(price[i]) # This doesn't execute because an exception was thrown
print(price[i]) # Neither does this
To get the result you're looking for, this would work:
price = [100] # creates a 'price' list with 1 element: [100]
for i in range(0, 2): # Start at index 0
print(price[i]) # Print current index
price.append(price[i]) # Append current value of price[i] to the price list
To ensure everything appended as you expected you can test it with len:
print(len(price))
Output:3
However, it is a preferred way of appending as @smci has shown in his/her answer.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55291189%2findex-and-lists-index-out-of-range%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
5 Answers
5
active
oldest
votes
5 Answers
5
active
oldest
votes
active
oldest
votes
active
oldest
votes
If you are just trying to append to a list, trying to do that with an index won't exactly work because that index isn't present in the list:
somelist = []
somelist[0] = 1
IndexError
So just use append
for i in range(1,3):
price.append(price[i-1])
add a comment |
If you are just trying to append to a list, trying to do that with an index won't exactly work because that index isn't present in the list:
somelist = []
somelist[0] = 1
IndexError
So just use append
for i in range(1,3):
price.append(price[i-1])
add a comment |
If you are just trying to append to a list, trying to do that with an index won't exactly work because that index isn't present in the list:
somelist = []
somelist[0] = 1
IndexError
So just use append
for i in range(1,3):
price.append(price[i-1])
If you are just trying to append to a list, trying to do that with an index won't exactly work because that index isn't present in the list:
somelist = []
somelist[0] = 1
IndexError
So just use append
for i in range(1,3):
price.append(price[i-1])
answered Mar 22 at 0:43
C.NivsC.Nivs
3,0801518
3,0801518
add a comment |
add a comment |
You're trying to append items to a list, or more precisely to initialize a list with repeated copies of something. Here are Pythonic ways to do that:
# Use a list comprehension
>>> price = [100 for _ in range(3)]
[100, 100, 100]
# Use itertools.repeat
>>> import itertools
>>> list(itertools.repeat(100, 3))
[100, 100, 100]
These are both faster than (repeatedly) doing append()
, which is O(N), so repeatedly doing append()
is O(N^2) on a long list, which gets very slow.
(Btw if you know a priori the list will have at least N elements, and N is large, you could initialize it to price = [None] * N
and you get [None, None, None...]
. Now you can directly assign to them. But, explicitly doing append is better practice for beginners.)
add a comment |
You're trying to append items to a list, or more precisely to initialize a list with repeated copies of something. Here are Pythonic ways to do that:
# Use a list comprehension
>>> price = [100 for _ in range(3)]
[100, 100, 100]
# Use itertools.repeat
>>> import itertools
>>> list(itertools.repeat(100, 3))
[100, 100, 100]
These are both faster than (repeatedly) doing append()
, which is O(N), so repeatedly doing append()
is O(N^2) on a long list, which gets very slow.
(Btw if you know a priori the list will have at least N elements, and N is large, you could initialize it to price = [None] * N
and you get [None, None, None...]
. Now you can directly assign to them. But, explicitly doing append is better practice for beginners.)
add a comment |
You're trying to append items to a list, or more precisely to initialize a list with repeated copies of something. Here are Pythonic ways to do that:
# Use a list comprehension
>>> price = [100 for _ in range(3)]
[100, 100, 100]
# Use itertools.repeat
>>> import itertools
>>> list(itertools.repeat(100, 3))
[100, 100, 100]
These are both faster than (repeatedly) doing append()
, which is O(N), so repeatedly doing append()
is O(N^2) on a long list, which gets very slow.
(Btw if you know a priori the list will have at least N elements, and N is large, you could initialize it to price = [None] * N
and you get [None, None, None...]
. Now you can directly assign to them. But, explicitly doing append is better practice for beginners.)
You're trying to append items to a list, or more precisely to initialize a list with repeated copies of something. Here are Pythonic ways to do that:
# Use a list comprehension
>>> price = [100 for _ in range(3)]
[100, 100, 100]
# Use itertools.repeat
>>> import itertools
>>> list(itertools.repeat(100, 3))
[100, 100, 100]
These are both faster than (repeatedly) doing append()
, which is O(N), so repeatedly doing append()
is O(N^2) on a long list, which gets very slow.
(Btw if you know a priori the list will have at least N elements, and N is large, you could initialize it to price = [None] * N
and you get [None, None, None...]
. Now you can directly assign to them. But, explicitly doing append is better practice for beginners.)
edited Mar 22 at 9:26
answered Mar 22 at 0:57
smcismci
15.6k678109
15.6k678109
add a comment |
add a comment |
The problem is you are assigning at an index too great for the length of the array.
for i in range(1, 3):
This initializes i to 1. Since arrays are zero-indexed, and the length of your array is 1 on the first pass, you will hit an assignment out of range error
at the line you mentioned (when i=1
).
Here is a minimal example showing the issue:
my_array = ["foo"]
my_array[1] = "bar" # throws assignment out of range error
add a comment |
The problem is you are assigning at an index too great for the length of the array.
for i in range(1, 3):
This initializes i to 1. Since arrays are zero-indexed, and the length of your array is 1 on the first pass, you will hit an assignment out of range error
at the line you mentioned (when i=1
).
Here is a minimal example showing the issue:
my_array = ["foo"]
my_array[1] = "bar" # throws assignment out of range error
add a comment |
The problem is you are assigning at an index too great for the length of the array.
for i in range(1, 3):
This initializes i to 1. Since arrays are zero-indexed, and the length of your array is 1 on the first pass, you will hit an assignment out of range error
at the line you mentioned (when i=1
).
Here is a minimal example showing the issue:
my_array = ["foo"]
my_array[1] = "bar" # throws assignment out of range error
The problem is you are assigning at an index too great for the length of the array.
for i in range(1, 3):
This initializes i to 1. Since arrays are zero-indexed, and the length of your array is 1 on the first pass, you will hit an assignment out of range error
at the line you mentioned (when i=1
).
Here is a minimal example showing the issue:
my_array = ["foo"]
my_array[1] = "bar" # throws assignment out of range error
answered Mar 22 at 0:43
Ryan RappRyan Rapp
1,0381017
1,0381017
add a comment |
add a comment |
You can't assign a value to a list directly why this list has note a previous size defined. You have to use append to add elements to the position you want.
Check:
# Check the value on our initial position
print(price[0])
for i in range(1, 3):
price.append(price[i-1])
print(price[i])
add a comment |
You can't assign a value to a list directly why this list has note a previous size defined. You have to use append to add elements to the position you want.
Check:
# Check the value on our initial position
print(price[0])
for i in range(1, 3):
price.append(price[i-1])
print(price[i])
add a comment |
You can't assign a value to a list directly why this list has note a previous size defined. You have to use append to add elements to the position you want.
Check:
# Check the value on our initial position
print(price[0])
for i in range(1, 3):
price.append(price[i-1])
print(price[i])
You can't assign a value to a list directly why this list has note a previous size defined. You have to use append to add elements to the position you want.
Check:
# Check the value on our initial position
print(price[0])
for i in range(1, 3):
price.append(price[i-1])
print(price[i])
answered Mar 22 at 0:51
Isac MouraIsac Moura
688
688
add a comment |
add a comment |
That will not print out:
100
100
You initialized a list with 1 element, the size of that list is 1. However your range starts at 1 for the for
loop , what's really happening is:
price = 100 # assigns 'price' to 100
price = [price] # creates a 'price' list with 1 element: [100]
for i in range(1, 3): # The list is 0-indexed, meaning price[0] contains 100
print(price[0]) # prints 100 as it should
price[i] = price[i - 1] # i is 1, price[i] is not an assigned value, i.e: you never assigned price[1]
price.append(price[i]) # This doesn't execute because an exception was thrown
print(price[i]) # Neither does this
To get the result you're looking for, this would work:
price = [100] # creates a 'price' list with 1 element: [100]
for i in range(0, 2): # Start at index 0
print(price[i]) # Print current index
price.append(price[i]) # Append current value of price[i] to the price list
To ensure everything appended as you expected you can test it with len:
print(len(price))
Output:3
However, it is a preferred way of appending as @smci has shown in his/her answer.
add a comment |
That will not print out:
100
100
You initialized a list with 1 element, the size of that list is 1. However your range starts at 1 for the for
loop , what's really happening is:
price = 100 # assigns 'price' to 100
price = [price] # creates a 'price' list with 1 element: [100]
for i in range(1, 3): # The list is 0-indexed, meaning price[0] contains 100
print(price[0]) # prints 100 as it should
price[i] = price[i - 1] # i is 1, price[i] is not an assigned value, i.e: you never assigned price[1]
price.append(price[i]) # This doesn't execute because an exception was thrown
print(price[i]) # Neither does this
To get the result you're looking for, this would work:
price = [100] # creates a 'price' list with 1 element: [100]
for i in range(0, 2): # Start at index 0
print(price[i]) # Print current index
price.append(price[i]) # Append current value of price[i] to the price list
To ensure everything appended as you expected you can test it with len:
print(len(price))
Output:3
However, it is a preferred way of appending as @smci has shown in his/her answer.
add a comment |
That will not print out:
100
100
You initialized a list with 1 element, the size of that list is 1. However your range starts at 1 for the for
loop , what's really happening is:
price = 100 # assigns 'price' to 100
price = [price] # creates a 'price' list with 1 element: [100]
for i in range(1, 3): # The list is 0-indexed, meaning price[0] contains 100
print(price[0]) # prints 100 as it should
price[i] = price[i - 1] # i is 1, price[i] is not an assigned value, i.e: you never assigned price[1]
price.append(price[i]) # This doesn't execute because an exception was thrown
print(price[i]) # Neither does this
To get the result you're looking for, this would work:
price = [100] # creates a 'price' list with 1 element: [100]
for i in range(0, 2): # Start at index 0
print(price[i]) # Print current index
price.append(price[i]) # Append current value of price[i] to the price list
To ensure everything appended as you expected you can test it with len:
print(len(price))
Output:3
However, it is a preferred way of appending as @smci has shown in his/her answer.
That will not print out:
100
100
You initialized a list with 1 element, the size of that list is 1. However your range starts at 1 for the for
loop , what's really happening is:
price = 100 # assigns 'price' to 100
price = [price] # creates a 'price' list with 1 element: [100]
for i in range(1, 3): # The list is 0-indexed, meaning price[0] contains 100
print(price[0]) # prints 100 as it should
price[i] = price[i - 1] # i is 1, price[i] is not an assigned value, i.e: you never assigned price[1]
price.append(price[i]) # This doesn't execute because an exception was thrown
print(price[i]) # Neither does this
To get the result you're looking for, this would work:
price = [100] # creates a 'price' list with 1 element: [100]
for i in range(0, 2): # Start at index 0
print(price[i]) # Print current index
price.append(price[i]) # Append current value of price[i] to the price list
To ensure everything appended as you expected you can test it with len:
print(len(price))
Output:3
However, it is a preferred way of appending as @smci has shown in his/her answer.
edited Mar 22 at 1:09
answered Mar 22 at 0:56
GKEGKE
557418
557418
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55291189%2findex-and-lists-index-out-of-range%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Issue is when trying to access python[i], then it throws index out of range. Left statement is not even
evaluated
– Apolozeus
Mar 22 at 0:42
You're trying to append items to a list, see below. You can't just assign a value at nonexistent index positions and expect the list to automatically append or grow itself.
– smci
Mar 22 at 0:58
1
(Btw if you know a priori the list will have at least 3 elements, you could initialize it to
price = [None] * 3
and you get[None, None, None]
. Now you can directly assign to them. But, explicitly doing append is better practice.)– smci
Mar 22 at 1:01