What I want to get is
[a][b][c]
Getting each index from an array a=[a,b,c]. I’m using this to approach a value in dictionary.
All I could find was .append() but this returns me [a,b,c] not [a][b][c]
This is the function that I made
Def loop():
Newlist = []
for i in a:
Newlist.append(i)
return Newlist
You want to append a list of one value, not a single value. i.e.
>>> new_list = []
>>> new_list.append([1])
>>> new_list.append([2])
>>> new_list.append([3])
[[1], [2], [3]]
So in the method you'd do something like this:
def loop():
new_list = []
for i in a:
new_list.append([i])
return new_list
Try this:
Create a new list inside the loop that gets reset each time, add your variable, then add the new list to the parent list.
You can also grab individual lists from the parent list using the following: Newlist[1]
Def loop():
Newlist = []
for i in a:
temp_list = []
temp_list.append(I)
Newlist.append(temp_list)
return Newlist
Related
When I have a list I need to clear, I usually just reassign it to a new empty list but is that the correct way or should I 'del' it first
example:
mylist = [1,2,3,4,5]
mylist = []
or
mylist = [1,2,3,4,5]
del mylist
mylist = []
Regards
TL;DR: the first one is good, no need to del first.
Both examples end up in the same exact situation: there's the original list object, which has 0 references to it, and there's a new list object which is bound to the name mylist.
I am trying to append an int value to a bunch of list variables all at once. Is there a for loop or such a function that would allow me to do that? Like I would like to append the val int to all list variables defined below.
val = 100
list_1=[]
list_2=[]
list_3=[]
list_4= []
Create a list containing all the lists, then use a loop:
val = 100
list_1 = []
list_2 = []
list_3 = []
list_4 = []
list_of_lists = [list_1, list_2, list_3, list_4]
for li in list_of_lists:
li.append(val)
Caution: do not be tempted to create list_of_lists in the following way:
list_of_lists = [[]] * 4
This will create a single list with 4 references to it, and changes done through 1 of them will be seen by all the other.
However, you can do
list_of_lists = [[] for _ in range(4)]
for li in list_of_lists:
li.append(100)
print(list_of_lists)
# [[100], [100], [100], [100]]
For something like this I would prefer a function to do so, as it is likely you'll do this again.
def appendAll(value, *args):
for listItem in args:
listItem.append(value)
This allows you to add a value to any set of lists. It doesn't require you to setup a list of variables as *args lets you pass any number of arguments and creates a tuple which lets us loop through each list and append our value to each list.
list1 = []
list2 = []
list3 = []
val = []
#now we can append val to all the lists or some of them
appendAll(val, list1, list2, list3)
My list named myList is not getting updated.
I'm defining it inside a function and I'm using it inside that function
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
myList = []
a = []
for i in range(len(nums)):
# print("---i",nums[i])
# print(a[0])
for j in range(i+1,len(nums)):
# print("----j",nums[j])
for k in range(i+2,len(nums)):
# print("-----k",nums[k])
if nums[i]+nums[j]+nums[k] == 0:
print("m into it now for i",nums[i],"j",nums[j],"k",nums[k])
print("oooo",myList)
a.append(nums[i])
a.append(nums[j])
a.append(nums[k])
# print(myList)
myList.append(a)
print("....",myList)
print("---",a)
a.clear()
print(myList)
Getting output as:
[[], [], [], []]
Python treat everything as object.
When you have a list like:
my_list = [1,2,3]
Here my_list is a reference to the the list [1,2,3] stored in memory.
Now if you pass my_list to any other function or use it in any other object like you have append the a in myList, so here basically python use this as reference to the original list. And now myList has stored the reference of a inside it.
That's why when you clear the contents of a, it also affects the content of myList.
You don't have to clear the content of list a. Just re-initialize it every time in for loop like this.
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
myList = []
for i in range(len(nums)):
# print("---i",nums[i])
# print(a[0])
for j in range(i+1,len(nums)):
# print("----j",nums[j])
for k in range(i+2,len(nums)):
# print("-----k",nums[k])
if nums[i]+nums[j]+nums[k] == 0:
print("m into it now for i",nums[i],"j",nums[j],"k",nums[k])
print("oooo",myList)
a = []
a.append(nums[i])
a.append(nums[j])
a.append(nums[k])
# print(myList)
myList.append(a)
print("....",myList)
print("---",a)
print(myList)
UPDATE:
As Artog mentioned in comments
You can easily see this in action by running print(list(map(hex,map(id, myList)))) at the end of the function instead. This will show that the memory address is the same for all entries with the original code, but different with the new.
I have a list of dictionaries:
list = [{"id":2, "date": "2018-07-12"}]
Now I want to generate some nice output and have a function for it:
def generateOutput(myList):
outputList = []
for l in myList:
l['date_short'] = "Jul-12"
outputList.append(l)
return outputList
And here's where the desaster starts:
output = generateOutput(list)
output is fine but list that I need for further calculation and shouldn't have the date_short at all got a new key and is:
list = [ {"id":2, "date": "2018-07-12", "date_short": "Jul-12" }]
How to overcome this?
You are modifying the dictionaries in myList in-place. Instead, you probably want to copy them individually before adding new values to them. Try this:
def generateOutput(myList):
outputList = []
for l in myList:
output = l.copy()
output['date_short'] = "Jul-12"
outputList.append(output)
return outputList
Also, you should avoid naming a variable list since list is the name of a predefined type in Python.
Pass a copy of the variable to the function by using the copy module.
import copy
list = [{"id":2, "date": "2018-07-12"}]
def generateOutput(myList):
outputList = []
for l in myList:
l['date_short'] = "Jul-12"
outputList.append(l)
return outputList
generateOutput(copy.copy(list))
I have a list of names my_names = ["A","B","C"]
I have a function that can takes each name from a list and returns several lists of information for that name.
def my_function(name):
return list1, list2, list3
For each name list1, list2, list3 are different.
I want to write a function that wouldn't need any user input but would return a list with 3 lists inside.
def my_function():
for name in my_list:
# Part I don't know how to do
name_list = list1, list2, list3
# A_list for "A", B_list for "B", C_list for "C"
return A_list, B_list, C_list
The only thin I don't know is how to make python introduce new empty lists depending on the name in my_list
A dictionary is best, but you can have a list of lists. Just make a main list: name_list = [] then append each list to it: name_list.append(list1), etc. Then reference each list using its index, then the elements in that list with a secondary index. For example,
def my_function():
for name in my_list:
name_list = []
name_list.append(list1)
name_list.append(list2)
name_list.append(list3)
return name_list
Then if you want to access the second element in the first list from the returned function, you would do so like:
name_list[0][1]
It's hard to say more without knowing more about your problem, but this will work, it's just not optimal.
You can create a nested list with n numbers of sublists, where n is any given number of lists
n = 3
nested_list = [[]] * n
# returns [[],[],[]]
#function that takes n, n=3
def create_nested_list(n):
nested_list = [[]] * n
return nested_list
nested list = create_nested_list(n)
You can append items in the nested list's lists by indexing, for instancce nested_list[0]=["A"] will append the number "A" to the first sublist, nested_list[1]=["B"]to the second and nested_list[2]=["C"] to the third sublist, so nested_list = [["A"],["B"],["C"]]