I am very new to Python and I can't seem to figure out how I can have two lists communicate with each other.
Here is what I am trying to achieve:
List 1 = [a, b, c]
List 2 = [1, 2, 3]
List 1 = 'b'
print(List 2)
Output: 2
I am looking for the code to evaluate the position of the item in List 1 and output the result of List 2 at the same exact position. How could I do that?
If both lists are incremented numbers, can I use the range?
Thank you in advance.
Python uses zero-based indexing. That means, the first element of List_1, a has an index 0, the second b has index 1, and so on.
If you tried accessing List_1 elements using List_2 like this List_1[List_2[0]] then you won't be able to access the first element because List_2 does not contain 0.
Related
I am writing a function that contains a list of numbers, and I need to find a way to count the occurrences of the numbers 1 and 2, only for the last 3 values of the list.
I obviously know of the .count() function, but I'm wondering if there's a way to use that only between a given index, in this case that index would be ((len(history-3), (len(history)), history being a list containing only values 1 and 2.
TL;DR: What is a way to count occurrences of values in a list between given indexes.
As Rocky Li suggest you can get the last three elements of a list by slicing it history[-3:]. You can then use the count function on the slice to get the count of 1 and 2 in the last three spots in the list.
For example:
>>> history = [1, 2, 1, 2, 1, 2, 1, 2, 1]
>>> count_1 = history[-3:].count(1)
>>> count_2 = history[-3:].count(2)
>>> count_1
2
>>> count_2
1
Use negative slicing to get last n values and count using count().
lst[-3:].count(2) # counts number of 2 from last three elements of list lst.
lst[-3:].count(1) # counts number of 1 from last three elements of list lst.
List has in-built count method for counting values.
You could slice the list and then count
arr = [2,1,3,3]
arr[-3:].count(3) # 2
And you could do exactly the same with indices as indicated here
arr[start:stop].count(3) # items start through stop-1
arr[start:].count(3) # items start through the rest of the array
arr[:stop].count(3) # items from the beginning through stop-1
arr[:].count(3) # a copy of the whole array
I hope this is of any use.
I have the following arrays:
a=[1,2,3,4]
b=['car','apple','orange']
I'm trying to iterate through arrays using:
for first,second in zip(a,b):
print(first,second)
But it prints all of the values at at time. How can I print 1st element from a array and 1st element from b array and so on?
You can use the [] operator to print the nth element of any array.
We can use a for loop to achieve a constant n value like this:
for i in range(3):
print(a[i], b[i])
Replace 3 with the length of both arrays, as the length should be the same.
You have two lists of differing lengths. Therefore, in order to access the values in pairs you could (probably should) use the zip() function.
If you don't want to use zip() then you need to start by determining the length of the shortest list then you can safely iterate over them. Something like this:
a = [1, 2, 3, 4]
b = ['car', 'apple', 'orange']
for k in range(len(min(a, b, key=len))):
print(a[k], b[k])
Output:
1 car
2 apple
3 orange
I have to define a function that prints out the list in reversed order. I'm not allowed to use str(), reversed(), .reverse or slicing method, and I must use only 1 for in loop. It's just about printing it reversed so the output printed vertically doesn't matter. I'm so lost please help :(
Try this (lst is the list you want to reverse):
lst = [0, 1, 2, 3, 4]
print(*(lst[len(lst) - idx - 1] for idx in range(len(lst))))
The previous code prints
4 3 2 1 0
I want to create a new list.
The new list will be 4 elements.
X = [0, 1, 2, 3]
Each of the 4 elements will be sums from 50 lists in a bigger list.
This bigger list has 50 elements all list. Inside each of the 50 nested lists.
Each of the nestedlists have these 5 elements
Nestedlist = [str, int, int, float, float]
['Ohio', 11568495, 11568495, 262851.0, 44824.9]
In this part I've sorted through the data and changed elements 1-4 in the 50 nestedlists in to integers and floating numbers.
This is how I turned elements 1-4 into int and float:
for i, sd in enumerate(statesData):
sd = sd.strip().split(',')
if i: # omit element 0
sd[1:] = int(sd[1]), int(sd[1]), float(sd[3]), float(sd[4])
statesData[i] = sd
Now I want to find the sum of elements 1 2 3 4 of the nested lists and create a new list X (shown above):
So this is what I have:
sums = []
for e in statesData:
if e:
e = sum(e[1]), sum(e[2]), sum(e[3]), sum(e[4])
sums.append(e)
The output should look like this:
sums = [sum all nested lists element 1, sum of nested lists element 2, sum of nested lists element 3, sum of nested lists element 4]
the output I am getting is
unsupported operand type for +: int and str
How can I take a specific elements from multiple nested lists and make use of them?
If I want to use every element 2 of lists 1:50 inside list X
I feel this should be a lot easier. Even tho I am new I feel like this would be a common question. To take the same elements of multiple lists inside a larger list and play with the data.
The issue is your for loop declaration,
for e in range(len(statesData)):
If len(statesData) is 4, then e will be 0,1,2,3 during the run of the loop. However, the code treats e as a list, indexing it multiple time here:
e[1:5] = sum(e[1]), sum(e[2]), sum(e[3]), sum(e[4])
Another issue is the sum, as it needs to take a list of values, not individual ints.
It would help if I could see what statesData looks like. But, assuming that you want to get it in chunks of 4, you could do something like this...
for e in range(0, len(statesData), 4):
newVal = sum(statesData[e], statesData[e+1], statesData[e+2], statesData[e+3])
sums.append(e)
This for loop counts by 4, so e will be 0, 4, 8, etc. Then, it uses e as an index to get 4 values of statesData. So the first loop it gets 0,1,2,3 and sums them. Then it gets 4,5,6,7 and sums them, so on and so on. It then appends that summation to the sums list. I'm not sure this is exactly what you are looking for, so let me know where I went wrong. But the specific error of int is not subscriptable is coming form the fact e is declared as an int in the for loop.
You can use zip and map to apply operations in a columnwise direction:
allStates = list(map(sum,[*zip(*statesData)][1:]))
Beginner here, learning python, was wondering something.
This gives me the second element:
list = [1,2,3,4]
list.index(2)
2
But when i tried this:
list = [0] * 5
list[2] = [1,2,3,4]
list.index[4]
I get an error. Is there some way to pull the index of an element from an array, no matter what list it's placed into? I know it's possible with dictionaries:
info = {first:1,second:2,third:3}
for i in info.values:
print i
1
2
3
Is there something like that for lists?
The index method does not do what you expect. To get an item at an index, you must use the [] syntax:
>>> my_list = ['foo', 'bar', 'baz']
>>> my_list[1] # indices are zero-based
'bar'
index is used to get an index from an item:
>>> my_list.index('baz')
2
If you're asking whether there's any way to get index to recurse into sub-lists, the answer is no, because it would have to return something that you could then pass into [], and [] never goes into sub-lists.
list is an inbuilt function don't use it as variable name it is against the protocol instead use lst.
To access a element from a list use [ ] with index number of that element
lst = [1,2,3,4]
lst[0]
1
one more example of same
lst = [1,2,3,4]
lst[3]
4
Use (:) semicolon to access elements in series first index number before semicolon is Included & Excluded after semicolon
lst[0:3]
[1, 2, 3]
If index number before semicolon is not specified then all the numbers is included till the start of the list with respect to index number after semicolon
lst[:2]
[1, 2]
If index number after semicolon is not specified then all the numbers is included till the end of the list with respect to index number before semicolon
lst[1:]
[2, 3, 4]
If we give one more semicolon the specifield number will be treated as steps
lst[0:4:2]
[1, 3]
This is used to find the specific index number of a element
lst.index(3)
2
This is one of my favourite the pop function it pulls out the element on the bases of index provided more over it also remove that element from the main list
lst.pop(1)
2
Now see the main list the element is removed..:)
lst
[1, 3, 4]
For extracting even numbers from a given list use this, here i am taking new example for better understanding
lst = [1,1,2,3,4,44,45,56]
import numpy as np
lst = np.array(lst)
lst = lst[lst%2==0]
list(lst)
[2, 4, 44, 56]
For extracting odd numbers from a given list use this (Note where i have assingn 1 rather than 0)
lst = [1,1,2,3,4,44,45,56]
import numpy as np
lst = np.array(lst)
lst = lst[lst%2==1]
list(lst)
[1, 1, 3, 45]
Happy Learning...:)
In your second example, your list is going to look like this:
[0, 0, [1, 2, 3, 4], 0, 0]
There's therefore no element 4 in the list.
This is because when you set list[2], you are changing the third element, not updating further elements in the list.
If you want to replace a range of values in the list, use slicing notation, for example list[2:] (for 'every element from the third to the last').
More generally, the .index method operates on identities. So the following will work, because you're asking python where the particular list object you inserted goes in the list:
lst = [0]*5
lst2 = [1,2,3,4]
lst[2] = lst2
lst.index(lst2) # 2
The answer to your question is no, but you have some other issues with your code.
First, do not use list as a variable name, because its also the name of the built-in function list.
Secondly, list.index[4] is different than list.index(4); both will give errors in your case, but they are two different operations.
If you want to pull the index of a particular element then index function will help. However, enumerate will do similar to the dictionary example,
>>> l=['first','second','third']
>>> for index,element in enumerate(l):
... print index,element
...
output
0 first
1 second
2 third