Showing posts with label slicing. Show all posts
Showing posts with label slicing. Show all posts

Wednesday, 24 January 2024

List slicing: Select and manipulate the elements of a list

List slicing in Python is an effective method for selecting and manipulating particular segments of a list. A slice is placed within square brackets, similar to an index, and consists of three integers separated by colons.

 

Syntax


new_list = original_list[start:stop:step]

 

start (optional): Specifies the starting index for the slice. If omitted, slicing begins from the list's start (index 0).

 

stop (optional): Determines the end index for the slice, not including the element at this index. By default, it's set to the length of the list, indicating that slicing continues up to this point.

 

step (optional): Defines the interval between elements in the slice. The default value is 1, which includes every element. Positive values mean forward iteration, while negative values indicate backward traversal.

 

Let’s experiment with below list.

>>> primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
>>> primes
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]

 

Example 1: Get 2nd, 3rd and 4th elements of a list.

>>> primes[1:4]
[3, 5, 7]

 

Example 2: Get everything from the fourth element to the end

>>> primes[4:]
[11, 13, 17, 19, 23, 29, 31]

Example 3: Get the elements from start to stop with a step size 2.

>>> primes[::2]
[2, 5, 11, 17, 23, 31]

Example 4: Reverse the list (step -1)

>>> primes[::-1]
[31, 29, 23, 19, 17, 13, 11, 7, 5, 3, 2]

 

List slicing creates a new list, without modifying the original.

>>> new_slice = primes[1:4]
>>> 
>>> primes
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
>>> 
>>> new_slice
[3, 5, 7]

 

‘new_slice’ is slice form the elements at index 1 to the index 4 (exclusive).

 

As slice creates a new list, updating the values in a slice do not affect the original list. You can confirm the same from below snippet.

>>> new_slice[1] = 37
>>> 
>>> new_slice
[3, 37, 7]
>>> 
>>> primes
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]

 

Manipulate the elements using list slicing

primes[1:3] = [37, 41]

Above snippet set primes[1] to 37 and primes[2] to 41.

>>> primes
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
>>> 
>>> primes[1:3] = [37, 41]
>>> 
>>> primes
[2, 37, 41, 7, 11, 13, 17, 19, 23, 29, 31]

 

Delete the elements using list slicing

‘del primes[1:3]’ delete the elements at indexes 1 and 2.

>>> primes
[2, 37, 41, 7, 11, 13, 17, 19, 23, 29, 31]
>>> 
>>> del primes[1:3]
>>> 
>>> primes
[2, 7, 11, 13, 17, 19, 23, 29, 31]

 

Inserting elements

>>> primes
[2, 7, 11, 13, 17, 19, 23, 29, 31]
>>> 
>>> primes[1:1] = [3, 5]
>>> 
>>> primes
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]

[1:1]: This is a slice operation. In slicing, the first number (before the colon) is the start index, and the second number (after the colon) is the stop index. Here, both the start and stop indices are 1. This means the slice starts and ends at index 1, effectively selecting a zero-length portion of the list right at index 1.

 

primes[1:1] = [3, 5]

Above snippet add the element 3 and 5 at index 1.

 


Previous                                                 Next                                                 Home

Friday, 2 September 2022

String slicing in Java

String slicing is about fetching a sub string from given string. Java String class provides subString method to fetch a sub string from given string.

 

subString method is available in below overloaded forms.

public String substring(int beginIndex)
public String substring(int beginIndex, int endIndex)

 

Get the substring from starting index

‘substring(int beginIndex)’ method returns a string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string. Here the beginIndex is inclusive.

String str1 = "hello world";
String subStr1 = str1.substring(6); // Return 'world'

 

'subString' method throws StringIndexOutOfBoundsException, if beginIndex is negative or larger than the length of this String object.

 

Get the substring between start and end indexes

‘substring(int beginIndex, int endIndex)’ method returns a string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex. Here the the beginning index is inclusive and endIndex is exclusive.

 

String str2 = "Java is a high level programming language";
String subStr2 = str2.substring(10, 14); // Return 'high'

'subString' method throws StringIndexOutOfBoundsException, if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.

 

Find the below working application.

 

SubStringDemo1.java

package com.sample.app.strings;

public class SubStringDemo1 {

	public static void main(String[] args) {
		String str1 = "hello world";
		String subStr1 = str1.substring(6); // Return world

		System.out.println("str1 : " + str1);
		System.out.println("subStr1 : " + subStr1);

		// Throws StringIndexOutOfBoundsException if beginIndex is negative or larger
		// than the length of this String object
		try {
			str1.substring(-1);
		} catch (StringIndexOutOfBoundsException e) {
			System.err.println(e);
		}

		try {
			str1.substring(100);
		} catch (StringIndexOutOfBoundsException e) {
			System.err.println(e);
		}

		String str2 = "Java is a high level programming language";
		String subStr2 = str2.substring(10, 14); // Return 'high'

		System.out.println("\nstr2 : " + str2);
		System.out.println("subStr2 : '" + subStr2 + "'");

		// throws StringIndexOutOfBoundsException, if the beginIndex is negative, or
		// endIndex is larger than the length of this String object, or beginIndex is
		// larger than endIndex.
		try {
			str2.substring(-1, 5);
		} catch (StringIndexOutOfBoundsException e) {
			System.err.println(e);
		}

		try {
			str2.substring(5, 100);
		} catch (StringIndexOutOfBoundsException e) {
			System.err.println(e);
		}

		try {
			str2.substring(5, 1);
		} catch (StringIndexOutOfBoundsException e) {
			System.err.println(e);
		}
	}

}

 


Output

str1 : hello world
subStr1 : world
java.lang.StringIndexOutOfBoundsException: begin -1, end 11, length 11
java.lang.StringIndexOutOfBoundsException: begin 100, end 11, length 11

str2 : Java is a high level programming language
subStr2 : 'high'
java.lang.StringIndexOutOfBoundsException: begin -1, end 5, length 41
java.lang.StringIndexOutOfBoundsException: begin 5, end 100, length 41
java.lang.StringIndexOutOfBoundsException: begin 5, end 1, length 41

 

References

https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/lang/String.html

 

Previous                                                 Next                                                 Home

Thursday, 13 June 2019

Nio: Buffer slicing

You can create a sub buffer from existing buffer using slice() method. Sliced buffer and original buffer shares same data. That is Modifications to the sliced buffer will cause the original buffer to be modified and vice versa. 

ByteBuffer byteBuffer = ByteBuffer.allocate(10);

byteBuffer.put((byte) 2);
byteBuffer.put((byte) 3);
byteBuffer.put((byte) 5);
byteBuffer.put((byte) 7);

ByteBuffer slicedBuffer = byteBuffer.slice();

Test.java
package com.sample.app;

import java.io.IOException;
import java.nio.ByteBuffer;

public class Test {

 private static void printMetaInfo(String message, ByteBuffer byteBuffer) {
  System.out.println(message);
  System.out.printf("Limit : %d\n", byteBuffer.limit());
  System.out.printf("Capacity : %d\n", byteBuffer.capacity());
  System.out.printf("Position : %d\n", byteBuffer.position());
 }

 private static void printBuffer(String message, ByteBuffer byteBuffer) {
  System.out.println(message);
  for (int i = 0; i < byteBuffer.capacity(); i++) {
   System.out.print(byteBuffer.get(i) + " ");
  }
  System.out.println();
 }

 public static void main(String... args) throws IOException {
  ByteBuffer byteBuffer = ByteBuffer.allocate(10);

  byteBuffer.put((byte) 2);
  byteBuffer.put((byte) 3);
  byteBuffer.put((byte) 5);
  byteBuffer.put((byte) 7);

  ByteBuffer slicedBuffer = byteBuffer.slice();

  String msg = "Meta information of the buffer";
  printMetaInfo(msg, byteBuffer);

  msg = "Content of the buffer";
  printBuffer(msg, byteBuffer);

  msg = "\nMeta information of the sliced buffer";
  printMetaInfo(msg, slicedBuffer);

  msg = "Content of the sliced buffer";
  printBuffer(msg, slicedBuffer);
  
  byteBuffer.put((byte)11);
  byteBuffer.put((byte)13);
  
  System.out.println("\nAdded 2 more elements into the buffer");
  
  msg = "\nMeta information of the buffer";
  printMetaInfo(msg, byteBuffer);

  msg = "Content of the buffer";
  printBuffer(msg, byteBuffer);

  msg = "\nMeta information of the sliced buffer";
  printMetaInfo(msg, slicedBuffer);

  msg = "Content of the sliced buffer";
  printBuffer(msg, slicedBuffer);
 }
}


Output

Meta information of the buffer
Limit : 10
Capacity : 10
Position : 4
Content of the buffer
2 3 5 7 0 0 0 0 0 0

Meta information of the sliced buffer
Limit : 6
Capacity : 6
Position : 0
Content of the sliced buffer
0 0 0 0 0 0

Added 2 more elements into the buffer

Meta information of the buffer
Limit : 10
Capacity : 10
Position : 6
Content of the buffer
2 3 5 7 11 13 0 0 0 0

Meta information of the sliced buffer
Limit : 6
Capacity : 6
Position : 0
Content of the sliced buffer
11 13 0 0 0 0



Previous                                                 Next                                                 Home