I am trying to create an array and then clear it using a function, but the terminal keeps displaying 'list index out of range'.
duplicates = []
def ClearArray():
for index in range(100):
duplicates[index].append("")
ClearArray()
print(duplicates)
The instruction is to Initialise the global array Duplicates, which is a 1D array of 100 elements of data type STRING, and set all elements to empty string using a function.
You are getting the error because you are initializing an empty list and then trying to access elements inside of that list.
In the first iteration of the for loop, you attempt to access duplicates[0] but the list is empty, and therefore the list index out of range exception is raised. You can resolve this by replacing duplicates[index].append("") with duplicates.append("").
You can read more about python lists here.
In addition, according to python's PEP8 function names should be lowercase, with words separated by underscores as necessary to improve readability.
Putting it all together:
duplicates = []
def clear_array():
for index in range(100):
duplicates.append("")
clear_array()
print(duplicates)
To remove all elements of a list, you can use clear, like so:
duplicates.clear()
I am not sure what you mean by clear, but when you create a list/array in python it will not have data
In case you need to add some data
duplicates = []
print(len(duplicates)) # length should be zero
for i in range(100):
dupicates.append(i)
In case you need to clear all the data in the list
print(len(duplicates)) # Should print 100 from the above for loop
duplicates.clear()
print(len(duplicates)) # Should be 0 again considering we have cleared the data
In case you are trying to create an array of arrays
duplicates = [[]] * 100
print(duplicates) # should show you 100 lists in a list
You are trying to get something that doesn't exist.
Your list duplicates = [] has nothing in it. Therefore duplicates[0] does not exist, which is why you are getting list index out of range.
In your example:
def ClearArray():
for index in range(100):
duplicates[index].append("")
The first iteration of your for loop accesses duplicates[index] where index = 0, Which throws the error.
When you append, you add to the end. So there is no need to specify an index. So this below will work fine:
def ClearArray():
for index in range(100):
duplicates.append("")
First create a non-empty array.
Then repeat deleting the first item of this array as many times as there are items in your array.
array = [43,54,65,76]
def ClearArray(array_to_clear):
for index in range(len(array_to_clear)):
del array_to_clear[0]
ClearArray(array)
print(array)
If you don't want to delete the items of the list but you want to replace each item with an empty string, then i recommend this code :
array = [43,54,65,76]
def ClearArray(array_to_clear):
for index in range(len(array_to_clear)):
array_to_clear[index] = ""
ClearArray(array)
print(array)
Related
I have s empty array. For example: base=[]. Then i want to insert "Tofiq"string to 3 th element. If i use print(base[3]) it must return"Tofiq" string. Please help me about it!
list cannot have empty nodes, hence fill the list till the required index or use dictionary
You either have to add intermediate elements to the list or use a dictionary instead of a list.
base = []
index = 3
base += [None]*(index-len(base)+1)
base[index] = "ToFig"
or
base = dict()
base[3] = "ToFig"
When you assign 'Tofiq' to index 3 of the empty list (for example, base[3] = 'Tofiq'), it will give IndexError. You should initialize your list instead of creating an empty list.
Currently, I have a list as such:
aList = [1,2,3,4,5]
and what I'm trying to do is to emulate 'aList[index] = item' function in python. the program prompts the user for input of negative index and the item to replace.
enter negative index: -2
enter item to replace: 7
this would give me:
[1,2,3,7,5]
since, when the index is negative, python starts counting from the back of the list. Here's my code:
aList = [1,2,3,4,5]
index = int(input("Enter index:"))
item = int(input("Enter item:"))
j = -1 #-1 means the counter should begin with -1 not 0
start = len(aList)-1 #i want python to start from the back of the list
while j<start:
if j == index:
aList[j] = item
j-=1
print(lst)
I'm getting an infinite loop because of the j-=1 and I'm wondering if I'm emulating it correctly?
I think first you need to clear you concept about array.
What is Array.?
Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers1, and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
Array In Python
To define a list you simply write a comma separated list of items in square brackets:
myList=[1,2,3,4,5,6]
This looks like an array because you can use "slicing" notation to pick out an individual element - indexes start from 0. For example
print myList[2]
will display the third element, i.e. the value 3 in this case. Similarly to change the third element you can assign directly to it:
myList[2]=100
The slicing notation looks like array indexing but it is a lot more flexible. For example
myList[2:5]
is a sublist from the third element to the fifth i.e. from myList[2] to myList[4]. notice that the final element specified i.e. [5] is not included in the slice.
Also notice that you can leave out either of the start and end indexes and they will be assumed to have their maximum possible value. For example
myList[5:]
is the list from List[5] to the end of the list and
myList[:5]
is the list up to and not including myList[5] and
myList[:]
is the entire list.
List slicing is more or less the same as string slicing except that you can modify a slice. For example:
myList[0:2]=[0,1]
has the same effect as
myList[0]=0
myList[1]=1
Finally is it worth knowing that the list you assign to a slice doesn't have to be the same size as the slice - it simply replaces it even if it is a different size.
I am not sure why you need a loop, when you can just access the elements by index:
aList = [1,2,3,4,5]
index = int(input("Enter index:"))
item = int(input("Enter item:"))
aList[index] = item
Of course your loop is infinite...the variable 'j' keeps getting more negative and you're comparing it so 'start', which is the length of the list minus one.
I was writing a function to save unique values returned by a list "list_accepted_car" to a set "unique_accepted_ant". list_car_id is list with the value ['12','18','3','7']. When i run the code i am getting error , "unhashable list ". Can anyone suggest me what is the error?
list_accepted_car = [] #set to store the value list_accepted_car
unique_accepted_car = set() #set to store the value unique_accepted_car
num_accepted = 2 #predifined value for the number of cars allowed to enter
def DoIOpenTheDoor(list_car_id): #list_ant_id is a list of cars allowed to enter
if len(list_accepted_car) < num_accepted:
if len(list_car_id) > 0:
list_accepted_car.append(list_car_id[0:min(len(list_car_id),num_accepted-len(list_accepted_car))])
unique_accepted_list = set(list_accepted_car)
print unique_accepted_list
return list_accepted_car
Under the assumption that list_car_id looks like: [1,2,3,4,5].
You add in list_accepted_car a sublist of list_car_id, so list_accepted_car will look like [[1,2]] i.e. a list of a list.
Then you should change
unique_accepted_list = set(list_accepted_car)
to
unique_accepted_list = set([x for y in list_accepted_car for x in y])
which will extract each element of the sublist and provide a flatten list. (There exists other options to flatten a list of list)
You are saving a list of lists, which can't be converted to a set. You have to flatten it first. There are many examples of how to do it (I'll supply one using itertools.chain which I prefer to python's nested comprehension).
Also, as a side note, I'd make this line more readable by separating to several lines:
list_accepted_car.append(list_car_id[0:min(len(list_car_id),num_accepted-len(list_accepted_car))])
You can do:
from itertools import chain
# code ...
unique_accepted_list = set(chain.from_iterable(list_accepted_car))
The best option would be to not use a list at all here, and use a set from the start.
Lists are not hashable objects, and only hashable objects can be members of sets. So, you can't have a set of lists. This instruction:
list_accepted_car.append(list_car_id[0:min(len(list_car_id),num_accepted-len(list_accepted_car))])
appends a slice of list_car_id to list_accepted_car, and a slice of a list is a list. So in effect list_accepted_car becomes a list of lists, and that's why converting it to a set:
unique_accepted_list = set(list_accepted_car)
fails. Maybe what you wanted is extend rather than append? I can't say, because I don't know what you wanted to achieve.
for i in xrange(6):
arr[i]=map(int,raw_input().strip().split())
it is showing
IndexError: list assignment index out of range
You could use a list comprehension to do it:
arr = [map(int, raw_input("enter values for row %d: " % i).strip().split())
for i in xrange(6)]
print arr
You have two problems :
First, you do not initialize the list before using it. Thus, arr is used as a list, even though it may have been created as another type of variable.
Second, you want to change the value for index i when there is no value for this index.
You can either create a list of six elements beforehand : arr = [ 0,0,0,0,0,0] or you can add the elements to the list as you create them : for i in xrange(6): arr.append(map(int,raw_input().strip().split()))
I do not know if it possible to create a list of a given size without giving values in python, though =/
you can do it like this
final=[]
for i in range(6):
final.append(list(map(int,input().split())))
Now you have all your inputs in a list final
I want to create a python 2D list, but i will not know the ecaxt dimensions that the list has to be initialized while writing the program.
For example i want a list like this
edgelist = [[3,5], [2,5], [4,6], ...]
The inner list will have two numbers. But the number of inner list will not be known while coding. the numbers will be assigned after initializing through a loop.
My code is :
edgelist = []
val = 0
for every_list in req_data:
for temp in range(1,len(every_list)):
edgelist[val].append(every_list[0])
edgelist[val].append(every_list[temp])
val = val+1
When val == 0 the list appends the value. But the next iteration it shows the error as IndexError: list index out of range...
edgelist = []
It means that edgelist is an empty list. So, edgelist[0] will not be able to get anything. That is why it is throwing that error. What you should do is
edgelist.append([every_list[0], every_list[temp]])
This will create a two element list with every_list[0] and every_list[temp] and add that list to edgelist. So, edgelist becomes a list of lists or a 2-D list.
Also, if req_data already has two element lists, then you can simply do
for every_list in req_data:
edgelist.append(every_list[:])
This will create copies of elements in req_data and add it directly to edgelist. Its better to use list comprehension, like this
edgelist = [every_list[:] for every_list in req_data]