How a Python code to store integer in list and then find the sum of integer stored in the List - python-3.x

List of integer value passed through input function and then stored in a list. After which performing the operation to find the sum of all the numbers in the list
lst = list( input("Enter the list of items :") )
sum_element = 0
for i in lst:
sum_element = sum_element+int(i)
print(sum_element)

Say you want to create a list with 8 elements. By writing list(8) you do not create a list with 8 elements, instead you create the list that has the number 8 as it's only element. So you just get [8].
list() is not a Constructor (like what you might expect from other languages) but rather a 'Converter'. And list('382') will convert this string to the following list: ['3','8','2'].
So to get the input list you might want to do something like this:
my_list = []
for i in range(int(input('Length: '))):
my_list.append(int(input(f'Element {i}: ')))
and then continue with your code for summation.
A more pythonic way would be
my_list = [int(input(f'Element {i}: '))
for i in range(int(input('Length: ')))]
For adding all the elements up you could use the inbuilt sum() function:
my_list_sum = sum(my_list)

lst=map(int,input("Enter the elements with space between them: ").split())
print(sum(lst))

Related

How to convert a tuple list string value to integer

I have the following list:
l = [('15234', '8604'), ('15238', '8606'), ('15241', '8606'), ('15243', '8607')]
I would like to converted it such that the tuple values are integers and not string. How do I do that?
Desired output:
[(15234, 8604), (15238, 8606), (15241, 8606), (15243, 8607)]
What I tried so far?
l = [('15234', '8604'), ('15238', '8606'), ('15241', '8606'), ('15243', '8607')]
new_list = []
for i in `l:
new_list.append((int(i[0]), i[1]))
print(tuple(new_list))
This only converts the first element i.e. 15234, 15238, 15241, 15243 into int. I would like to convert all the values to int. How do I do that?
The easiest and most concise way is via a list comprehension:
>>> [tuple(map(int, item)) for item in l]
[(15234, 8604), (15238, 8606), (15241, 8606), (15243, 8607)]
This takes each tuple in l and maps the int function to each member of the tuple, then creates a new tuple out of them, and puts them all in a new list.
You can change the second numbers into integers the same way you did the first. Try this:
new_list.append((int(i[0]), int(i[1]))

How can I do this with list comprehension? Or how can I extract every even position element from list and store it in a list?

p = [i.text.strip() for i in soup.select('p.card-text')]
j = []
for i in p:
if p.index(i)%2 == 0:
j.append(i)
I am doing this because I only want to extract even position element from my list p.
Is there any other way to do this (to get only even position element from list)?
If not, how can I write the code above using list comprehension? I have extracted even position element using this code. I want to know of any other method I can apply or how to write list comprehension for the above code?
You can try the following by using list comprehension along with enumerate in python
p = [i.text.strip() for index,i in enumerate(soup.select('p.card-text')) if index%2==0]
Um... simply slice:
j = p[::2]
Or if select returns a list (looks like it does), do it earlier to save work:
soup.select('p.card-text')[::2]

Get index of a list with tuples in which the first element of the tuple matches pattern

I have a list of tuples:
countries = [('Netherlands','31'),
('US','1'),
('Brazil','55'),
('Russia','7')]
Now, I want to find the index of the list, based on the first item in the tuple.
I have tried countries.index('Brazil'), I would like the output to be 2. But instead, that returns a ValueError:
ValueError: 'Brazil' is not in list
I am aware that I could convert this list into a pd DataFrame and then search for a pattern match within the first column. However, I suspect there is a faster way to do this.
You can use enumerate() to find your index:
Try:
idx = next(i for i, (v, *_) in enumerate(countries) if v == "Brazil")
print(idx)
Prints:
2

How to subtract adjacent items in list with unknown length (python)?

Provided with a list of lists. Here's an example myList =[[70,83,90],[19,25,30]], return a list of lists which contains the difference between the elements. An example of the result would be[[13,7],[6,5]]. The absolute value of (70-83), (83-90), (19-25), and (25-30) is what is returned. I'm not sure how to iterate through the list to subtract adjacent elements without already knowing the length of the list. So far I have just separated the list of lists into two separate lists.
list_one = myList[0]
list_two = myList[1]
Please let me know what you would recommend, thank you!
A custom generator can return two adjacent items at a time from a sequence without knowing the length:
def two(sequence):
i = iter(sequence)
a = next(i)
for b in i:
yield a,b
a = b
original = [[70,83,90],[19,25,30]]
result = [[abs(a-b) for a,b in two(sequence)]
for sequence in original]
print(result)
[[13, 7], [6, 5]]
Well, for each list, you can simply get its number of elements like this:
res = []
for my_list in list_of_lists:
res.append([])
for i in range(len(my_list) - 1):
# Do some stuff
You can then add the results you want to res[-1].

List comprehension of 3 nested loops and the output is based on if-else condition

Is it possible to convert this into a list comprehension? For example, I have a list v. On the source code below, v = dictionary.keys()
v = ["naive", "bayes", "classifier"]
I have the following nested list t.
t = [["naive", "bayes"], ["lol"]]
The expected output O should be:
O = [[1 1 0], [0 0 0]]
1 if the dictionary contains the word and 0 if not. I'm creating a spam/ham feature matrix. Due to the large dataset, I'd like to convert the code below into a list comprehension for a faster iteration.
ham_feature_matrix = []
for each_file in train_ham:
feature_vector = [0] * len(dictionary)
for each_word in each_file:
for d,dicword in enumerate(dictionary.keys()):
if each_word == dicword:
feature_vector[d] = 1
ham_feature_matrix.append(feature_vector)
I couldn't test this, but this translates as:
ham_feature_matrix = [[[int(each_word == dicword) for dicword in dictionary] for each_word in each_file] for each_file in train_ham]
[int(each_word == dicword) for dicword in dictionary] is the part which changes the most compared to your original code.
Basically, since you're iterating on the words of the dictionary, you don't need enumerate to set the matching slots to 1. The comprehension builds the list with the result of the comparison which is 0 or 1 when converted to integers. You don't need to get the keys since iterating on a dictionary iterates on the keys by default.
The rest of the loops is trivial.
The issue I'm seeing here is that you're iterating on a dictionary to create a list of booleans, but the order of the dictionary isn't fixed, so you'll have different results each time (like in your original code) unless you sort the items somehow.

Resources