Python 2D lists appending data to a location - python

Wondering if someone can help me on this. I know I can append data to a 1D list by using .append. What I am having trouble figuring out is how to append data to a 2D list and have Python place the data in the right list in the right spot.
I need to create a program that runs x times (with each name having 2 pairs of values), and after each time append the user input to a list. So at the end, I need something like this:
[[Name] [1,2] [3,4]]
[[Name] [4,5] [6,7]]
etc….
How do I tell Python which List and position to place the Names and values in ?
This is what I have so far for code.
def main():
how_many = int(raw_input("How many to enter? "))
counter = 0
list = [ [], [] ]
while counter < how_many:
name = raw_input("Enter the Name ")
first_val = int(raw_input("Enter first_val "))
first_val2 = int(raw_input("Enter first_val2 "))
sec_val = int(raw_input("Enter sec_val "))
sec_val2 = int(raw_input("Enter sec_val2 "))
counter = counter + 1
main()
OK - so I modified the code and added in a line to append the data, after the line with the counter + 1.
list.append([[name],[first_val,first_val2], [sec_val,sec_val2]])
What I would now like to do is print the list out (via rows and columns), but am getting a IndexError. This occurs when I try to enter/print out more than 4 values. The error appears to be in the last line. Is there a way I can modify the code to stop this and print out as many values as have been requested by the user ?
for r in range(how_many):
for c in range (how_many):
print list [r][c]
And yes, I will look into using tuples as well at some point.

def main():
how_many = int(raw_input("How many to enter? "))
counter = 0
list = []
while counter < how_many:
name = raw_input("Enter the Name ")
first_val = int(raw_input("Enter first_val "))
first_val2 = int(raw_input("Enter first_val2 "))
sec_val = int(raw_input("Enter sec_val "))
sec_val2 = int(raw_input("Enter sec_val2 "))
list.append([[name], [first_val, first_val2], [sec_val, sec_val2]])
counter = counter + 1

Assume we are reading the values from stdin (as in the question body)
you can use lists:
list = []
....
list.append([[name], [first_val, first_val2], [sec_val, sec_val2]])
but a tuple seems to be a better fit here:
t = (name, (first_val, first_val2), (sec_val, sec_val2))
list.append(t)
Since the values are not likely to change, a tuple feels like the better choice.
Think about how a field would be accessed in each case:
list:
name = list[i][0][0]
tuple:
name = list[i][0]
Again...it just seem more natural...

Related

Adding elements to list after get 2 or more inputs on Python

def take_info(arr2,arr, number):
arr[0] = number
name = input()
arr[1] = name
grade = int(input())
arr[2] = grade
second_grade = int(input())
arr[3] = second_grade
arr2. append(arr)
def main():
number = int(input())
arr = [0] * 4
count =1
arr2 = // ? I dont know how to do it, range must be equal to count but how? Thats the point 1.
while number>0:
take_info(arr2,arr,number)
count +=1
number = int(input())
main()
take_info function must return while ' number >0 ', when the number is 0 or less than 0 loop would end. And I want to add these values and name to a list and the other list's each element should be list. Could anyone can help me ?
Any time you're repeating something, you probably want to use a loop. If you're using a loop to build a list, you probably want to use a list comprehension.
arr = [input() for _ in range(3)]
Given your updated question, I might do it like this:
def take_info(number):
return [number, input(), int(input()), int(input())]
def main():
return [take_info(number) for number in range(int(input()))]
print(main())
If it's important that the numbers count down instead of up, you can do that by modifying the range call so that it goes from N-1 to 0 instead of 0 to N-1.
Alternatively, if you want to have space separated inputs in one line, you can use this:
my_list = list(map(str,input().split()))
for i in range(len(my_list)):
if (isinstance(my_list(i), int)):
temp = int(my_list(i))
my_list.pop(i)
my_list.insert(i, temp)
Input: Car Hockey Cricket
my_list = ['Car', 'Hockey', 'Cricket']
Ofcourse, the data type would be the same here. You'd need to make changes after appending incase of int, float, etc.
The stereotype of Python is that “everything is a dict”. Your application might be such a case.
One way to organize the data you have coming in might be a dict where each entry is also a dict.
def take_info():
record = dict()
record['name'] = input('Name: ')
record['grade'] = int(input('Grade: '))
record['second_grade'] = int(input('Second grade: '))
return record
def main():
course_records = dict()
count = 0
number = int(input('ID number: '))
while number > 0:
course_records[number] = take_info()
count +=1
number = int(input('ID number: '))

Trying to add all Values [duplicate]

This question already has answers here:
'int' object not iterable
(2 answers)
Closed 2 years ago.
I'm a beginner in python but i have some knowledge with C++, My Problem is that I'm trying to get the sum of all the Values given by the user but i get this error 'int' object is not iterable so can someone help me please Here is my code
Food= int(input("Enter number of Food: "))
for x in range(Food):
Foodn = str(input("Enter Food Name: "))
Value = int(input("Enter Value: ))
The above code works
#--Getting the Sum of all Value
for j in Value:
j += Value
print(j)
First:
str(input())
becomes
input() #By default its a string but it doesn't really matter
Then:
if you are using j in the for loop it wont work because you are changing its value,
what you need to do is something like this
Food= int(input("Enter number of Food: "))
List = []
for x in range(Food):
Foodn = str(input("Enter Food Name: "))
Value = int(input("Enter Value: "))
List.append(Value)
Total = 0
for j in List:
Total += j
print(Total)
Value is just the last value that the user entered, not all the values they entered. You need to put them in a list if you want to loop over them.
Food= int(input("Enter number of Food: "))
values = []
for x in range(Food):
Foodn = str(input("Enter Food Name: "))
Value = int(input("Enter Value: "))
values.append(Value)
#--Getting the Sum of all Value
total = 0
for j in values:
total += j
print(total)
You seems to be pretty new to python. In my opinion, you should refer to Lists in Python. But the easy solution for your problem is given below-
Food= int(input("Enter number of Food: "))
total = 0
for x in range(Food):
Foodn = str(input("Enter Food Name: "))
Value = int(input("Enter Value: ))
total += Value
print(total)
One more thing which you should notice is that, input simply returns the entered data in string format. So, no need to typecast that with str().

How to access strings entered in loop?

This is the code.
n = int(input("Enter number of strings: "))
for i in range(n):
ai= input("Enter string ")
i=0
print(ai)
Why does it give last string and not the first string?
If I try to print a0 ,it gives error.
I know that I can use lists , but I didn't know about list when I wrote the program and now I have to change everything to use list.
Because you are overwriting the variable in each iteration of the loop, if you want to print all the strings added in the format you can use something like this
n = int(input('enter number of strings'));
ai = ''
for i in range(n):
ai += input('enter a string: ')+'\n'
i = 0
print(ai)
This will print your string.
You should use a list and append every input to the list instead:
n = int(input("Enter number of strings: "))
a = []
for _ in range(n):
a.append(input("Enter string: "))
print(a[0])

Basic list checker

I want to create a list, then enter an int, which will then add the int amount of strings to a list,then print it. So far so good:
list = []
number = int(raw_input("Enter a number: "))
while number > 0:
list.append(str(raw_input("Enter a word: ")))
number = number - 1
print list
However, how do I make it a little more advanced so that you cannot add the same string twice to the list?
You can keep a set of all the strings seen, only adding a string and if it has not been seen before, you don't need to keep a count variable either, you can loop until len(data) != number:
number = int(raw_input("Enter a number: "))
seen = set()
data = []
while len(data) != number:
inp = raw_input("Enter a word: ")
if inp not in seen:
data.append(inp)
seen.add(inp)
If the order was irrelevant you could just use a set altogether as sets cannot have dupes:
number = int(input("Enter a number: "))
data = set()
while len(data) != number:
inp = raw_input("Enter a word: ")
data.add(inp)
Check for whether the list already contain the entered string or not before appending. And don't use in-built keywords as variable names.
list_ = []
number = int(raw_input("Enter a number: "))
while number > 0:
x = raw_input("Enter a word: ")
if not x in list_:
list_.append(x)
number = number - 1
else:
print "Word is already available"
print list_
you can do something like this
mylist = []
number = int(raw_input("Enter a number: "))
while number > 0:
mystring = str(raw_input("Enter a word: "))
if mystring not in mylist:
mylist.append(mystring)
number = number - 1
else:
print('Choose different string')
next
print mylist
and try to avoid build-in function as variable name. Built-in functions are
https://docs.python.org/2/library/functions.html

Taking the sum of a list without sum()

I have a list that gets generated when a user inputs a random number they want. I want to add the sum together with out using sum(). How could I do this?
xAmount = int(input("How man numbers would you like to input: "))
numList = []
for i in range(0, xAmount):
numList.append(int(input("Enter a number: ")))
print(numList)
From here
Store the sum in a temp variable. Keep adding the input numbers to the temp variable:
xAmount = int(input("How man numbers would you like to input: "))
numList = []
numList_sum = 0
for i in range(0, xAmount):
inputted_number = int(input("Enter a number: "))
numList_sum += inputted_number
numList.append(inputted_number)
print(numList)
print(numList_sum)
You don't need a list at all.
xAmount = int(input("How man numbers would you like to input: "))
result = 0
for i in range(0, xAmount):
result = result + int(input("Enter a number: "))
print(result)
To sum a list just iterate over the list, adding up the individual values:
num_total = 0
for value in numList:
num_total += value
You could also use reduce but this might not meet your h/w requirements either:
from functools import reduce
from operator import add
num_total = reduce(add, numList, 0)

Categories

Resources