Query on Slicing a list in Python [duplicate] - python-3.x

This question already has answers here:
Understanding slicing
(38 answers)
Closed 5 days ago.
How do I print the reverse of a specific selection of a list ?
For example, I have a list,
a = [11,22,33,44,55,66,77,88]
I expect a[1:4:-1] to print [44,33,22], but it gives an empty list.
I have seen Understanding slicing, but I couldn't find an answer.

The python slicing syntax, when 3 parameters are provided, is [start:stop:step]
In order to get the value [44, 33, 22], you'd need to write the slice like this: a[3:0:-1]
This works because the slice starts at index 3, which has a value of 44, and the slice stops before index 0, meaning the last included index is 1 (with a value of 22), based on the step value of -1.

Related

for loop doesn't itterate through all the data? [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 1 year ago.
data = [1, 2, 3, 4, 5]
for x in data:
print(x)
if data.count(x) < 2:
data.remove(x)
Hello Guys,
so I am currently working through py.checkio.org and am at a point where I have to remove all the numbers that are unique in a list.
When I run my code without the if statement I get an output counting from 1 to 5. But once I run the for loop with the if statement the for loop only runs through the data for every second number and my output is 1 3 5. Can anyone please tell me what is happening here?
While the from #Stef and #0x5453 are both relevant to your problem. The comment from #ConnorTJ is patently wrong. The remove function does not remove the item at the index but the first occurrence of the item.
To answer your question, about what's going on here, let[s examine your code:
The first pass through the value of x is 1
You print the value of x
You then test to see if the number of occurrences of x is less than 2
Since the answer is yes, you proceed to remove the item from the list.
The second pass through the list the For loop picks up the next value in the list (at index 1) which is now the value 3
You print the value 3
You check to see if the count of 3 is less than 2
Since the count is less you remove that item from the list.
This process than continues
Simple solution, use filter()
Construct an iterator from those elements of iterable for which function returns true
it returns a list of the list items that the function returned true for.
example:
x = [1,1,2,2,3,4]
x = filter(lambda f: (x.count(f)<2), x)
x = list(x)
print(x)
or in short: print(list(filter(lambda f: (x.count(f)>=2),x)))
output is [1,1,2,2]

Reverse entire dictionary items [duplicate]

This question already has answers here:
How do I sort a dictionary by key?
(32 answers)
How do I sort a dictionary by value?
(34 answers)
Closed 2 years ago.
I know this may be a simple question but I'm having trouble reversing my dictionary. All the solutions I've seen haven't been working for me. I have a dictionary where the keys are strings and the values are either None or type int. I want to reverse the order so the last (key, value) pair is first and vice versa.
For example:
d = {"pointA": 100, "pointB": 140, "pointC": None, "pointD: None}
I want to reverse the dictionary to:
reversed_d = {"pointD": None, "pointC": None, "pointB": 140, "pointA": 100}
I've tried sorted(d.items(), reverse=True) and reversed(sorted(d.items()))
but I got an error of:
TypeError: '<' not supported between instances of 'int' and 'str'
You could do it this way.
Loop =>
for k,v in reversed(list(d.items())):
or just
reversed_d = reversed(list(d.items()))
since dictionaries are ordered by insertion order of the keys (since python 3.6, guaranteed since python 3.7), you can reverse the keys:
d = {"pointA": 100, "pointB": 140, "pointC": None, "pointD": None}
for k in reversed(d):
print(k)
From there, you can build a new dictionary by inserting key values in the reversed order, or create a generator to access the (Key, value) pairs in that order.

Sorting a list of strings items from an array [duplicate]

This question already has answers here:
Is there a built in function for string natural sort?
(23 answers)
Closed 3 years ago.
I'm new to python automation and wrote a script to get some port handles from Ixia and store into a list. I;m trynig to sort that port-handle where I see a problem.
I tried using the sort method but doesn;t work
>>> a
['1/1/11', '1/1/6']
>>> a.sort()
>>> a
['1/1/11', '1/1/6']
>>> d = a.sort()
>>> print(d)
None
>>>
Am i missing anything here .. kindly clarify
I want the output in the following format
1/1/6 1/1/11
Explanation
You are trying to sort a list of strings. Strings are naturally sorted in lexicographical_order, i.e. "10" < "11" < "2" < "5" < ..., so Python executes correctly what you want it to do. This being said, you need to transform your data into something that will be sorted as you want.
Solution
>>> a = ['1/1/11', '1/1/6']
>>> a
['1/1/11', '1/1/6']
>>> def to_tuple(string_representation):
... return tuple(int(i) for i in string_representation.split('/'))
...
>>> b = [to_tuple(element) for element in a]
>>> b.sort()
>>> b
[(1, 1, 6), (1, 1, 11)]
>>> a.sort(key=to_tuple)
>>> a
['1/1/6', '1/1/11']
Here we use the fact that tuple is sorted by default exactly how we want it to be sorted in your case (actually, it is also a lexicographical order, but now 11 is one element of a sequence and not two).
List b contains a transformed list, where each element is a tuple. And now sort will work as you want.
The second option, will be using a custom key operator. It is a function that returns a key to compare different elements of your list. In this case, key will be a corresponding tuple of integers and will be compared as you want.
Note 1
The second approach (with the key operator) will create an additional overhead during sorting as it will be called O(NlogN) times.
Note 2
You also tried using the result of sort function as a value, but it changes the given list in-place. If you want a sorted copy of your list, use sorted.

How to input arrays of numbers in one line(not one input in each line) for a given number of n elements and make a list in Python? [duplicate]

This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 4 years ago.
N=5
Input: 12345
Output: [1,2,3,4,5]
No need for map or lambda, you can just use the list() function or list comprehension;
an_array = input()
>>> 12345
print([int(x) for x in an_array])
>>> [1, 2, 3, 4, 5]
Iterate through input string (using For loops) and create array (using List).

range() returns the word itself [duplicate]

This question already has answers here:
Python 3 turn range to a list
(9 answers)
Closed 5 years ago.
I'm using python 3.6
when I use the range function in Python console, it didn't return an array, instead it shows the wording itself:
range(1, 5)
range(1,5)
print(range(1,5))
range(1,5)
How can I show the array?
The range() function in Python 3 returns an iterator, something you can iterate on, so you can use it as:
for x in range(1, 5):
print(x)
This iterator returns one value at a time, so it can be more memory efficient.
If you want to get a list, you can use this code:
list(range(1,3))

Resources