This question already has answers here:
How to create a number of empty nested lists in python [duplicate]
(2 answers)
Closed 3 years ago.
I am trying to create a nested list. The result would be something like [[0,1],[2,3],[0,4]] I tried the following and got an index out of range error:
list = []
list[0].append(0)
Is it not appending 0 to the first item in the list? How should I do this? Many thanks for your help.
A little typo, you should do:
list = [[]]
list[0].append(0)
You need to have a first element first...
Edit:
Use:
list = []
for i in range(3):
list.append([])
list[-1].append(0)
For that you'll need to append a list to a list first, i.e.:
list = []
list.append([])
list[0].append(0)
print(list)
# [[0]]
lst = []
lst.append([0,1])
lst.append([2,3])
lst.append([0,4])
print(lst)
How about this ? Or you need in the form of loop with constant set of numbers?
Related
This question already has answers here:
Checking whether a string starts with XXXX
(5 answers)
Apply function to each element of a list
(4 answers)
Closed 3 months ago.
I have a list that I want to edit. For all the elements that start with '[x]', I want the list to remove those elements and place them into new list. But for the new list, in doing so, it should remove the '[x]' from the front of the elements.
list1 = ['[x]final', '[x]gym', 'midterm', '[x]class', 'school']
list1 becomes:
list1 = ['midterm', 'school']
new list that was created from removing the elements that had '[x]' in the front:
new_list = ['final', 'gym', 'class']
I am new to coding and am having difficulties with this.
Since you are a beginner, the verbose way to do this is the following
list1 = ['[x]final', '[x]gym', 'midterm', '[x]class', 'school']
new_list = []
for s in list1:
if s.startswith("[x]"):
new_list.append(s[3:])
print(new_list)
However, you can take advantage of Python's list comprehension to do it in a single line, like this
list1 = ['[x]final', '[x]gym', 'midterm', '[x]class', 'school']
new_list = [s[3:] for s in list1 if s[0:3] == "[x]"]
print(new_list)
Both methods yield ['final', 'gym', 'class']
This question already has answers here:
How to extract the n-th elements from a list of tuples
(8 answers)
Get the nth element from the inner list of a list of lists in Python [duplicate]
(1 answer)
How to access the nth element of every list inside another list?
(3 answers)
Closed 1 year ago.
Not sure how to google this for the same reason I am not sure how to write the title.
basically if I have the array:
[[1,2,3],[4,5,6],[7,8,9]]
I want to pull say the 2nd(nth) item of each array and turn them into an array as such:
[2,5,8]
What is the quickest (preferably immediate) way to parse the array this way without using for-loops?
You can use list comprehension
x = [[1,2,3],[4,5,6],[7,8,9]]
y = [ele[1] for ele in x]
If you really don't want see loop or for, you can use map and lambda
x = [[1,2,3],[4,5,6],[7,8,9]]
y = list(map(lambda x:x[1],x))
If you don't consider a list comprehension a loop (even though it is certainly looping under the hood), you could accomplish this like:
list1 = [[1,2,3], [4,5,6], [7,8,9]]
list2 = [ e[1] for e in list1 ]
This question already has answers here:
Can't modify list elements in a loop [duplicate]
(5 answers)
Closed 3 years ago.
I am stuck on a problem due to a small portion of my code. I can't find why that portion of code is not working properly.
By debugging each portion of my code, I found which lines are causing unexpected results. I have written that lines below. I have defined the list here so that I do not have to copy my full code.
list1=["-7","-7","-6"]
for test in list1:
test=int(test)
print( type( list1[0] ) )
I expected type to be int but output is coming as str instead.
You need to modify the content of the list:
list1=["-7","-7","-6"]
for i in range(len(list1)):
list1[i] = int(list1[i])
print(type(list1[0]))
A more pythonic approach would be to use a comprehension to change it all at once:
list1 = [int(x) for x in list1]
Try this to convert each item of a list to integer format :
list1=["-7","-7","-6"]
list1 = list(map(int, list1))
list1 becomes [-7, -7, -6].
Now type(list1[0]) would be <class 'int'>
You forgot about appending the transformed value:
list1 = ["-7","-7","-6"]
list2 = [] # store integers
for test in list1:
test = int(test)
list2.append(test) # store transformed values
print(type(list2[0]))
This question already has answers here:
Different ways of clearing lists
(8 answers)
Closed 4 years ago.
list1 = [2,5,61,7,10]
list1.remove(list1[0:len(list1)-1])
print(list1)
I want to remove all elements from that list but it shows me syntax error.
Any idea how can I remove all elements and print the final result like []
To remove all list items just use the in-built .clear() function:
>>> list1 = [2,5,61,7,10]
>>> list1.clear()
>>> print(list1)
[]
>>>
If you want to remove all elements from a list, you can use the slice assignment:
list1[:] = []
But with list.remove(), you can only do it one-by-one:
for item in list(list1):
list1.remove(item)
Note I created a copy of list1 with the for loop because it's dangerous to modify what you're iterating over, while it's safe to modify the list while iterating over a copy of it.
To remove some of the items:
for item in list1[0:3]:
list1.remove(item)
Or just better yet, use slice assignment:
list1[0:3] = []
This question already has answers here:
Removing duplicates in lists
(56 answers)
Closed 5 years ago.
I have a list of strings in which there are a lot of repeated items. I would like to make a new list in which all items are present but there is only one occurrence of each item.
input:
mylist = ["hg", "yt", "hg", "tr", "yt"]
output:
newlist = ["hg", "yt", "tr"]
I actually have tried this code but did not return what I want:
newlist = []
for i in range(len(mylist)):
if mylist[i+1] == mylist[i]:
newlist.append(mylist[i])
You can simply use a set:
newlist = set(mylist)
Or, to retrieve exactly a list, but is can be useless depending what you are doing with:
nexlist = list(set(mylist))